Changing front-end image based on back-end variable change without reloading page in django
I'm using Django framework to monitor garbage fill ratio. I' m getting the data via IOT device with Raspberry Pi. So when the sensor data change, I want to change the image on front-end without page reload. So I want to see real time data on front-end. I searched about Django channels but I can not figure it out how to change image.
<body>
<h1 class="title">Garbage Monitoring System</h1>
<div class="trash-bin">
{% if binCapacity == 0 %}
<img src="static/images/0.png" alt="zeroGarbage" />
<p>Fill Ratio: 0%</p>
{% elif binCapacity == 25 %}
<img src="static/images/25.png" alt="%25 Garbage" />
<p>Fill Ratio: 25%</p>
{% elif binCapacity == 50 %}
<img src="static/images/50.png" alt="%50 Garbage" />
<p>Fill Ratio: 50%</p>
{% elif binCapacity == 75 %}
<img src="static/images/75.png" alt="%75 Garbage" />
<p>Fill Ratio: 75%</p>
{% elif binCapacity == 100 %}
<img src="static/images/100.png" alt="%100 Garbage" />
<p>Fill Ratio: 100%</p>
{% endif %}
</div>
</body>
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Upload file from html when block public access is true
I am using
django-s3direct
to file uploadhttps://github.com/bradleyg/django-s3direct
Using IAM role setting because I upload the file from the server on ECS container.
Now I set the
blockPublicAccess
ofS3
false.When uploading images from html, there comes error.
https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403
OK, it is understandable.
Browser try to access the for initiation.
However there is any way to upload file from browser when blockPublicAccess is true??
-
Test a decorated function in Python
I have a python function which is decorated.
@retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something"""
I've written tests for the given as below.
@patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """
But I am getting this error that says add_somehthing takes 1 positional argument.
TypeError: add_something() takes 1 positional argument but 3 were given
-
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data
Thanks in advance!
-
How to create an app to control a raspberry pi?
I would like to create a Cross-Platform app to control my raspberry pi.
I am new with app developing, but as I was reading more about it, I noticed that Kotlin or Flutter are good options to create an app for both iOS and android.
Does anyone have any recommendations on which to use? Also, do both Kotlin or Flutter allow raspberry pi connections?
Thank you!
-
Streaming RTSP Locally through HTML5
I am attempting to host a local website on my RaspberryPi using raspivid, and HTML 5. So far, I have managed to get the RTSP link, and view this live stream on VLC player across various devices. The link looks as follows:
RTSP://1XX.1XX.X.1XX:PORT/
Now attempting to embed this stream into the server site, I have tried the video tag;
<video src="rtsp://1XX.1XX.X.1XX:PORT"> Your browser does not support the VIDEO tag and/or RTP streams. </video>
which returns the error:
Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME
I have also tried the to directly embed the VLC player;
<OBJECT classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab" width="640" height="480" id="vlc" events="True"> <param name="Src" value="rtsp://1XX.1XX.X.1XX:PORT" /> <param name="ShowDisplay" value="True" /> <param name="AutoLoop" value="False" /> <param name="AutoPlay" value="True" /> <embed id="vlcEmb" type="application/x-google-vlc-plugin" version="VideoLAN.VLCPlugin.2" autoplay="yes" loop="no" width="640" height="480" target="rtsp://1XX.1XX.X.1XX:PORT" ></embed> </OBJECT>
this method displays 'plug in not supported' on chrome, and doesn't show at all on safari. I would preferably like to find a method of embedding this stream, without requiring specific browser plug-ins, as the server will be accessed by various devices and browsers on the network.
If anyone has any advice or ideas on how to get this up and running, or if this is possible at all, I'd be super grateful, as I've spent a couple of days on this now, and can't seem to find any relevant/up-to-date guidance on this anywhere.
If possible, I would like to avoid any port forwarding. I am happy to implement simple APIs if necessary, however I want to keep the project fairly 'bare bones', and not overcomplicate things. The website is static, and I'd prefer to not require any backend/PHP type stuff.
-
Why do my arguments given in the terminal not get parsed by argparse correctly?
I have a question about my code in python. I am supposed to define an input pin and an output pin in the command line. When the input pin gets an input (High or Low), it is supposed to pass it to the output pin. To test my code, I connected a button to my input pin and an LED to my output pin. I want to define my input pin and output pin in the command line using argparse, so I do not have to change the pins in the code every time I change the pins physically. My code worked before using argparse, but now after implementing argparse it does not do what it is supposed to (does nothing). My code looks like this:
import RPi.GPIO as GPIO import argparse parser = argparse.ArgumentParser() parser.add_argument('pin_in', type = int, help = 'Possible output pins: 3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40') parser.add_argument('pin_out', type = int, help = 'Possible input pins: 3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40') args = parser.parse_args() GPIO.setmode(GPIO.BOARD) #set pin numbering style GPIO.setup(args.pin_out,GPIO.OUT) #set pin_out as output pin GPIO.setup(args.pin_in,GPIO.IN, pull_up_down = GPIO.PUD_UP) #set pin_in as input pin def inputToOutput(pin_in, pin_out): #this method is supposed to read pin_in status (HIGH or LOW) and pass it to the output pin pin_out if GPIO.input(pin_in) == GPIO.LOW: GPIO.output(pin_out, GPIO.LOW) else: GPIO.output(pin_out, GPIO.HIGH) if __name__ == '__main__': GPIO.add_event_detect(args.pin_in, GPIO.BOTH, callback = lambda x: inputToOutput(args.pin_in, args.pin_out)) #this detects either a falling or rising edge and if an edge is detected, calls the inputToOutput method; #add_event_detect syntax is (input channel, rising/falling/both edges, callback function)
Name of my file is PinMonitor_argparse.py and I run the file in the terminal by:
python3 PinMonitor_argparse.py --pin_in 35 --pin_out 15
I first tried to pass the 35 and 15 without writing --pin_in and --pin_out first like
python3 PinMonitor_argparse.py 35 15
and got the notification in the terminal:
usage: PinMonitor_argparse.py [-h] [--pin_in PIN_IN] [--pin_out PIN_OUT]
So I added the --pin_in and --pin_out and the error
error: unrecognized arguments: 35 15
was gone. Now I do not get any error notification, but the code is still not changing the output pin status depending on the input pin status.
I am thankful for any suggestion in advance!
-
error: no matching function for call to 'MQTTClient::MQTTClient(int)' MQTTClient client = MQTTClient(256);
I'm working on an IoT project. ESP32 with AWS IoT Core.
I followed https://catalog.us-east-1.prod.workshops.aws/workshops/5b127b2f-f879-48b9-9dd0-35aff98c7bbc/en-US/module3/configure-esp32 for doing my project, But I received an Error message.
"LampProject:33:35: error: no matching function for call to 'MQTTClient::MQTTClient(int)' MQTTClient client = MQTTClient(256); "
-
using a string to reference a struct
I'm having troubles with a function in C using a string to reference a struct, the used code is included below
int Search_name (char nombre[],Nentrada user_number){ int result; int i; for (i = 0; i < user_number ;i++) { char *temp; asprintf(&temp,"user%d",i); printf("%s \n",temp); result = strcmp(nombre,user1.Nombre); } if (result != 0) { result = 1; } return result;}
The code is used in a function that is usposed to search for a string in the argument "nombre" of the struct "entrada", it works perfectly when i manually use the struct assignments "user1.Nombre, user2.Nombre..." nonetheless when I use the string temp (which switch between values user1,user2...) I keep receiving the error
error: request for member 'Nombre' in something not a structure or union|
Therefore I would like to know how can I aumatically switch the struct without having the issue.
-
How can i connect between Snowflake and IoT Sitewise to share data?
I am looking for any connector or any other ways that i can connect and get data from snowflake to IoT Sitewise.
-
Other websockets does not work when a websocket is pending
I use Django Channels and I have multiple websocket addresses. When I connect to a websocket, it gets and computes somethings from database and this process may take 10 seconds. But during this 10 seconds all of my websockets does not respond to any user and it yields a 502 Bad Gateway to every user.
It seems that all of my websockets are running by a single agent, and when it is pending, all other websockets does not respond anymore, until the agent becomes free. My code is some like the following code.
How can I solve this problem?
class SymbolConsumer(WebsocketConsumer): def connect(self): self.symbol_name = self.scope["url_route"]["kwargs"]["symbol_name"] async_to_sync(self.channel_layer.group_add)(self.symbol_name, self.channel_name) self.accept() self.send(time_consuming_function_1(self.symbol_name)) self.send(time_consuming_function_2(self.symbol_name)) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.symbol_name, self.channel_name ) def receive(self, text_data): pass
-
Django send full QuerySet in Channels
I am using Django Channels to build a game. It's a super simple multiplayer chance game. After user clicks a button the game starts and the server receives the data via Channels. I do the necessary calculations, database updates etc. Now I want to send data back to the browser. I do a filter query from the database and I would like to send the whole query back. I know I could take out the necessary data one by one and send them separately but I feel like there's a better way but I just can't figure it out.
When I would send the QuerySet like in views.py I get a
TypeError: Object of type QuerySet is not JSON serializable.
Sending the query using
list()
also gives me an errorValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
Is there a way I could send the whole QuerySet with Channels?
consumer.py async def send_message(self, event): room_name = event['room_name'] roomObj = cbr.objects.filter(room_name=room_name) cbObj = cb.objects.filter(room=roomObj) #cbObj is what I would like to send await self.send(text_data=json.dumps({ 'cb': cbObj # Gives TypeError }))