Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix port error when creating Django backend service on Google Cloud Run?
I have a Django REST backend image in which I tried to create a service for it on Google Cloud Run. In the Google Cloud Run, I set the port to 6000, and when I tried to create it, it showed these errors: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to MySQL server on '35.226.227.51' (115)") The user-provided container failed to start and listen on the port defined provided by the PORT=6000 environment variable. Default STARTUP TCP probe failed 1 time consecutively for container "backend" on port 6000. The instance was not started. The last 2 layers on the Dockerfile of my backend are: EXPOSE 6000 CMD python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:6000 I am not sure how to fix this for this is my first time trying to deploy a website. For the database error, I have checked the database credentials and configured my Django settings.py to connect to my Google Cloud SQL, MySQL instance with the public IP address as shown and made sure the configuration is correct, but not really sure why it is showing that error. Any help would be … -
Django/DRF GET list of objects including object with FK to that object
I have an API endpoint that returns a list of objects (Orders). class Order(models.Model): item_name = models.CharField(max_length=120) Each of these Orders also has multiple associated Statuses, which acts similar to tracking the location of a package. A new one is created whenever the status changes, with the new status and a timestamp. class OrderStatus(models.Model): status = models.CharField(max_length=30) timestamp = models.DateTimeField(auto_now_add=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="order_statuses") When I query a list of the current Orders, I want to return the most recent OrderStatus associated with it. Such as this: { "count": 2, "next": null, "previous": null, "results": [ { "item_name": "Something", "order_status": { "status": "Processing" "timestamp": "2023-09-25T12:31:12Z" } }, { "item_name": "Other Thing", "order_status": { "status": "Completed" "timestamp": "2023-08-15T10:41:32Z" } } ] } I have tried using prefetch_related() in my View, but that seems to be for the reverse situation (When the query is for the object that has the FK in it's class definition - which here would be if I wanted to list the fields on Order when I query for the OrderStatus). -
Google Charts - Very Slow Loading Time
I'm relatively new to web development and I like the look of Google Charts. I wanna load some Django data with it, but the load time is extremely slow. I have a simple chart here with only a single point. It takes 3-5 seconds to appear, after everything else on the webpage has already shown up. Am I doing anything wrong or could something be causing the lag? // chart google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Year'); data.addColumn('number', 'Msgs'); data.addRow([new Date('2023-08-25'), 5]) var options = { hAxis: { title: 'Time' }, vAxis: { title: 'Number of Messages' }, backgroundColor: '#2C2F33' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } Thank you. -
Django - Any ideas on how to mimic the way Amazon handles their progress bar? [closed]
I have tried using Bootstap, which can produce a strait line. But I like the way Amazon's progress bar has node bubbles that show a checkmark in them when it reaches a certain point. I have considered just using a preset image, but if I have like 6 nodes minimum, with multiple options that those nodes can be, that can be a lot of image files. And if something were to change in the flow, it could potentially be a lot of work to update these files. So looking for an alternative -
Getting invalid_grant when trying to exchange tokens using Django-oauth-toolkit
I am trying to use the django-oauth-toolkit but continually hitting an invalid_grant error. I believe I have followed the instructions at https://django-oauth-toolkit.readthedocs.io/en/latest/getting_started.html#oauth2-authorization-grants to the letter. I have created the following script to test with (mostly just extracted the code mentioned in the above page: import random import string import base64 import hashlib code_verifier = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(43, 128))) code_verifier = base64.urlsafe_b64encode(code_verifier.encode('utf-8')) code_challenge = hashlib.sha256(code_verifier).digest() code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8').replace('=', '') client_id = input("Enter client id: ") client_secret = input("Enter client secret: ") redirect_url = input("Enter callback url: ") print(f'vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge={code_challenge}&code_challenge_method=S256&client_id={client_id}&redirect_uri={redirect_url}') code = input("Enter code: ") print(f'enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "code={code}" -d "code_verifier={code_verifier}" -d "redirect_uri={redirect_url}" -d "grant_type=authorization_code"') The following shows the output (I haven't redacted the details, they are only temporary): (venv) (base) peter@Peters-MacBook-Air Intra-Site % python api_test.py Enter client id: sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N Enter client secret: GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng Enter callback url: https://192.168.1.44/authenticate/callback vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge=WiaJdysQ6aFnmkaO8yztt9kPBGUj-aqZSFVgmWYRBlU&code_challenge_method=S256&client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N&redirect_uri=https://192.168.1.44/authenticate/callback Enter code: hrLeADVEmQF8mDLKJXhAZJRQ2dElV7 enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" -d "code=hrLeADVEmQF8mDLKJXhAZJRQ2dElV7" -d "code_verifier=b'UDZGREwyR0ZVMjNCTzRBQlFaVlBUQk9TWkVRUDlCQzFSUTY1MkFNMUUzRTVCRVBNNlkwR0k4UEtGMUhaVVlTVkQ0QVowMzJUR0xLTDQ1U0VNOEtaWVcxT0tP'" -d "redirect_uri=https://192.168.1.44/authenticate/callback" -d "grant_type=authorization_code" (venv) (base) peter@Peters-MacBook-Air Intra-Site % curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" … -
Query child objects through parent model - Django
Is it possible to query all child objects through parent model and eventually get the subclass of every element in the queryset. models.py class employee(models.model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) def __str__(self): return self.first_name class teacher(employee): school=models.CharField(max_length=30) district=models.CharField(max_length=30) subject=models.CharField(max_length=30) class doctor(employee): hospital=models.CharField(max_length=30) specialty=models.CharField(max_length=30) If I make a query to get all employees queryset = employee.objects.all() How to get every employee's subclass without making queries for subclasses. Is the subclass repesented with a field in the parent model -
WebSocket with Django and Expo not working
I am building an expo app that uses Django for backend. For the app I need to use WebSocket. But when I try to connect to the WebSocket on my Django project, I get Not Found: /ws/ [25/Sep/2023 19:34:58] "GET /ws/ HTTP/1.1" 404 2678 This is my Expo code: const socket = React.useRef(new WebSocket('ws://myIP:8000/ws/')).current; console.log(socket) if (socket) { // Now you can safely work with the WebSocket object } else { console.error('WebSocket is undefined.'); } socket.onmessage = (event) => { console.log(event.data) // Handle incoming messages from the WebSocket server }; socket.onopen = () => { // WebSocket connection opened console.log("opened") }; socket.onclose = (event) => { // WebSocket connection closed }; socket.onerror = (error) => { // Handle WebSocket errors console.log("error") }; This is my Django code: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'channels', ] ASGI_APPLICATION = 'API.routing.application' routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from .consumers import YourWebSocketConsumer from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "API.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( [ path("ws/", YourWebSocketConsumer.as_asgi()), # Add more WebSocket consumers and paths as needed ] ), }) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class YourWebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async … -
Migrating an application with subdomains to a single URL
I currently have an application that uses django-tenants with subdomains for each tenant (tenant1.domain.com, tenant2.domain.com...) It uses individual authentication, the auth models are in the schemas So my question is: Is it possible to migrate to a single URL model both for authentication and navigation? I tried many solutions, some managed to authenticate my user, but none managed to make me navigate in a tenant using a "schema-free" URL In short none maintained/created a session -
'InnerDoc' object has no attribute 'pk'
I'm encountering an issue with Elasticsearch-dsl when trying to use a custom serializer with Django REST framework. The error message I'm getting is: 'InnerDoc' object has no attribute 'pk' This error originates in the line serializer = self.serializer_class(results, many=True) from the following code snippet in my PaginatedElasticSearchAPIView: class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) I've checked my serializer, and it seems to have the primary key ("id") defined correctly: class OfficeSerializer(serializers.ModelSerializer): # ... class Meta: model = Office fields = [ "id", # ... ] My Elasticsearch document, defined as OfficeDocument, also appears to have the primary key ("id") defined correctly: @registry.register_document class OfficeDocument(Document): # ... class Django: model = Office fields = [ "id", # ... ] Despite this, I was still encountering the "'InnerDoc' object has no attribute 'pk'" error. Then I recreated all models without explicitly setting ids and removed the ids references … -
Using a Custom Django FilterSet and OrderingFilter at the Same Time Breaks My FilterSet
So I have MyFilterSet and CustomOrderingFilter both working perfectly by themselves but when I try to put both into the view at the same time the FilterSet breaks. I've removed the unnecessary business logic from the functions and just included the parts that matter. I tried to put the OrderingFilter inside the FilterSet (to no avail). (There are no errors generated. I'm using Django 1.14, Python 2.7.17 and PostgreSQL 10.23 and it will be near impossible to change those versions at the moment but if changing is the answer I'd like to know that too.) in filters.py: class MyFilterSet(FilterSet): id = filters.NumberFilter(name='id', lookup_expr='exact') class Meta: model = TheModel fields = list() exclude = [] class CustomOrderingFilter(OrderingFilter): fields_related = { 'vendor': { 'data_type': 'text', 'loc': 'thing__vendor',}, } def get_ordering(self, request, queryset, view): param = request.query_params.get(self.ordering_param) if param: return param return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering in self.fields_related.keys(): return queryset.order_by(ordering) return queryset in views.py class getMyListAPIView(generics.ListAPIView): serializer_class = MySerializer filter_class = MyFilterSet filter_backends = [CustomOrderingFilter] def get_queryset(self): models = TheModel.objects return models -
How to implement connection requests in a room? [closed]
There is a room that can create any user, and he will automatically become its administrator. There may be people in this room who have entered the room code in a specific field. Now the user connects immediately, but I need that after sending the room code, the administrator sitting in the room receives a connection request (relatively speaking, block with the name of the person connecting and the “accept” and “reject” buttons). If the administrator accepts the connection, the user will be in the room, otherwise not. How to do it? Websockets? If yes, can you provide more details? Or maybe there is another way to implement all this? -
Why cant I add a new page to my Django project?
I am trying to add another page to my Django project. At first the problem was that the tutorial I was using was asking to use url so i switched it to re_path but it is still not working and giving me many errors. Right now my urls.py looks like this: from django.contrib import admin from django.urls import path, re_path, include from myapp import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^hello/$', include (views.hello)), ] However I keep getting an error that says "File "C:\Program Files\Python311\Lib\site-packages\django\urls\resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<function hello at 0x000001C657C0F2E0>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." Amonge other errors for files I have not edited yet. -
Tuples in Django models
I want to write the whole word on the website when entering the product information by entering the first letter of the status field. But here it receives the information correctly, but only displays the first letter on the web page. class Product(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) def __str__(self): return self.get_status_display() This is one of the ways to display this field. <a><a>Status: </a>{{ product.status }}</a><br> -
Connect SQL Server in Django Socker
Outside of Docker, my app works well, and I can connect to two SQL Server databases, on two diferent servers. Inside Docker, I can't connect to the second DB. I ger a timeout error. Can someone help me? settings.py DATABASES = { 'default': { 'ENGINE' : config('DB_ENGINE'), 'NAME' : config('DB_DEFAULT_NAME'), 'USER' : config('DB_DEFAULT_USERNAME'), 'PASSWORD': config('DB_DEFAULT_PASS'), 'HOST' : config('DB_HOST_DEFAULT'), 'PORT' : '', 'OPTIONS': { 'driver': config('DATABASE_DRIVER'), }, }, 'otherbd': { 'ENGINE' : 'mssql', 'NAME' : 'serverbd', 'USER' : 'user', 'PASSWORD': 'pw', 'HOST' : '192.168.1.165', 'PORT' : '63649', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } views.py def ordens_e_ensaques(request): try: second_db = connections['otherbd'] cursor = second_db.cursor() # Consulta para obter as ordens cursor.execute("SELECT * FROM Ordens WHERE ORD_Estado = '1'") print('Consulta SQL de Ordens executada com sucesso!') resultados_ordens = cursor.fetchall() # Consulta para obter os ensaques cursor.execute("SELECT * FROM OrdensEnsaqueActivas") print('Consulta SQL de Ensaques executada com sucesso!') resultados_ensaques = cursor.fetchall() context = { 'resultados_ordens': resultados_ordens, 'resultados_ensaques': resultados_ensaques } return render(request, 'pages/producoes.html', context) except Exception as e: print("Erro ao conectar ao banco de dados: ", e) return HttpResponse("Erro ao conectar ao banco de dados: " + str(e)) -
Implementation of binary tree in django
i am planing to implement binary tree for recommendation where a user can enroll any number of user but i want to keep all the user in binary tree A / \ B c / \ / \ D E F G how can i store this data in database i have tried creating model class Tremodel(models.Model): refered_by = foreign key user left = foreign key user right = foreign key user how can i query 15 level from there where A is the root but for the B/C tree start from it and B/C is the root where tree can go up to any level i just need to calculate up to 15 level in its branch i tried creating the model i have shown above but i am totally confused how to query it` -
Fast Refresh not happening using React js and Django
Im very new to react js and Django and i want to experiment how the screen changes whenever i save the codes. But currently whenever i do the changes, i need to press the refresh button on the browser manually to check the changes. After a lot of research i found the way to automatically do that is via Fast Refresh. I have tried a lot of things for it to work using the links below but none have worked so far. https://dev.to/thestl/react-fast-refresh-in-django-react-kn7 Development server of create-react-app does not auto refresh I am using webpack 5.88.2, babel/core 7.22.20,react 18.2.0 Please let me know how i can do this. Thanks -
How can I integrate djangocms-link in Ckeditor
I would like to use the functionality of the djangocms-link Plugin within the Ckeditor suche that I can add any and numerous links to my text. So far I have only found this feature. But this does not provide the flexibility I need (to add multiple links in various positions. Thanks a lot -
Customizing Permissions and Groups models in Django
I want to modify the Permissions and Group models from django.contrib.auth. I have extended them but am unable to understand how to use these extended models in my project. I had researched about it again and again but could not find the solution. Can any one help me? I had to add two extra fields in Permission model and 4 additional fields in Group model. I had extended both models but when I replace the permissions attribute of Group class it gives error that local fields cannot replace existing. Further, I cannot use add/contribute to original class methods as it is dangerous to replace original files and is not a good programming practice too. Is there any way to change permissions in Group model. Secondly, how can I use these new models in User model? -
How to differentiate created objects and updated objects in Django bulk_create?
I am using bulk_create to create objects in one query. I set update_conflicts to True to update permission level if the record already exists. bulk_create returns the created and updated objects. How can I separate the created object and updated ones? class UserPermission(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='permissions') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='permissions') permission_level = models.SmallIntegerField(default=1) class Meta: unique_together = ('project', 'user') permissions = UserPermission.objects.bulk_create( user_permissions, update_conflicts=True, update_fields=['permission_level'], unique_fields=['project', 'user'], ) -
Receiving Sendgrid Inbound Email webhook attachments as strings (not files)
I'm receiving multiple inbound email webhook requests from Sendgrid (a Django/DRF application on my side) with attachments that are strings rather than actual files. This results in an error when trying to save the files (because 'str' object has no attribute 'file' when trying to file.read()). It apparently happens to approx. 5-10% of all inbound emails and seems to only happen with image files (JPGs, GIFs etc), I did not encounter a PDF file passed this way. Before saving the files I iterate over attachments-info keys to get a list of attachments, here's an example result [ '����\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00��\x10�Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x04\x01;\x00\x02\x00\x00\x00\r\x00\x00\x08J�i\x00\x04\x00\x00\x00\x01\x00\x00\x08X��\x00\x01\x00\x00\x00\x1a\x00\x00\x10��\x1c\x00\x07\x00\x00\x08\x0c\x00\x00\x00>\x00\x00\x00\x00\x1c�\x00\x00\x00\x08\x00..., <InMemoryUploadedFile: 40896630.pdf (application/octet-stream)> ] What exactly is this string? Why does that happen? How can I decode it (assuming all I have is the original file name and content type) -
"cannot cast type bigint to uuid" while changing db from sqLite3 to PostgressSql
So here is my Pet model and PetAttachmentImage model as well, in case if it can give any extra info. The problem is that I created my whole backend on Django using default engine (sqlite3) and now I need to deploy it on a cloud, in my case its neonDb - which uses postgres as engine. When I'm trying to migrate my data from sqlite3 on my local storage to postgress on neonDb I get this error - psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid So I've done my research and found similar problem even here on StackOverflow,however it's solution doesn't work in my case, and I don't understand why. Also I use uuid as my primary key, I created id only to make it explicit about the fact that I don't want to use it, and to alter it with my custom one if it's somehow still exists by default. class Pet(models.Model): id = models.BigIntegerField(blank=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, blank=False, null=False) name = models.CharField(max_length=150, default="Unnamed") animal = models.CharField(max_length=150, default="") breed = models.CharField(max_length=150, default="") location = models.CharField(max_length=150, blank=True, null=True) image = models.ImageField(upload_to='images/', default='images/pet.png', blank=True, null=True) description = models.TextField(max_length=1000, blank=True, null=True) info = models.TextField(max_length=1000, blank=True, null=True) def __str__(self): return f"{self.animal} … -
Bootstrap elements cause a reduction in width, which is not a proper behavior
As title says some bootstrap elements changes my whole website width, reducing it by 15px. I think that responsive elements cause this weird behavior. Code: <div class="px-4 py-5 my-5 text-center"> <img class="d-block mx-auto mb-4" src="{%static 'images/tinytools_logo.png'%}" alt="" width="100" height="100"> <h1 class="display-5 fw-bold text-body-emphasis">Tiny Tools - AI powered platform</h1> <div class="col-lg-6 mx-auto"> <p class="lead mb-4">Have you ever dreamt of a website that can instantly answer your questions or help you solve a test? Our advanced platform, powered by the mighty GPT-4, is here to assist you.</p> <div class="d-grid gap-2 d-sm-flex justify-content-sm-center"> </div> </div> </div> <div class="container col-xxl-8 px-4"> <div class="row flex-lg-row-reverse align-items-center g-5 "> <div class="col-10 col-sm-8 col-lg-6"> <img src="{% static 'images/ask_gpt_logo.jpeg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6"> <h1 class="display-5 fw-bold text-body-emphasis lh-1 mb-3">Ask GPT - AI chatbot</h1> <p class="lead">AI chatbot powered by GPT-4 analyzes your question and provides precise answers based on the latest knowledge.</p> <div class="d-grid gap-2 d-md-flex justify-content-md-start"> <button type="button" class="btn btn-warning btn-lg px-4 me-md-2">Tool</button> </div> </div> </div> </div> <div class="container col-xxl-8 px-4 py-5"> <div class="row flex-lg-row-reverse align-items-center g-5"> <div class="col-10 col-sm-8 col-lg-6 order-lg-2"> <img src="{% static 'images/lensgpt_logo.jpg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6 order-lg-1"> <h1 … -
I need to upload to profile pic
using base64 encoded and saved in database b'iVBORw0KGgoAAAANSUhEUgAABZ0AAALkCAYAAABkw5u0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAP+lSURBVHhe7N0JYBTl2Qfwf07CnXCHS4IIBEFJxCpRPIKohGIlFA9SbSteSMADRKv0a1W8ECoKAa2iVgselGClgIoEDwRRJChIuCSIHOFMgIRcm+z3PrMzyexkd7NJNskm/H84bvad2ZnZmXfemX323WcCvv/+ezvIr9jtjl0ijzabDUVFRejQoQPat2+PsLAwBAUFaeOJiOqLtE35+fnYv38/8vLyEBISorVNAQEBWtsljzIQEdUn45qK7VHDZuxHM1dlZubxlU1bHbUxTyLyrDbacvM8K5u/q/E8vxARucegs58xLmDlUYI6BQUF6N27N9q0aaOVExH5mz179uD48eMIDQ0tCzwLXoQTEZGveAryVhYA9scAsT+uE1F9qc... I need to upload profile pic I need to display image in circle in circle i need to get image from data base when user is login -
Live dashboard: django, dash or else?
I'm new to this kind of development, so I write hoping to have a feedback. I need to build a dashboard displaying several parameters (# ~100) taken from an OPC UA server. I also need to implement some logic based on the values to show if the parameters are within safety limits or not. I already used plotly + dash in the past, thus I decided to start using dash to build my dashboard together with a python script responsible to subscribe to the opcua datapoints I need to follow and constantly update a file with them. This file with all the values is then feeding the dash app which is set to update throughIntervals every sec. This gives me a live updating dashboard. Now I was wondering if there is a better way to design this. The dashboard has a general main page where some of the most important parameters are displayed. However there are also different tabs per subsystem/topic where the user can switch to and see all the available parameters of that subsystem at once. Here the problem I encountered is that in dash I can not share information within the Tabs. Thus if a datapoint is … -
I want to see or download the file in django admin uploaded by user from frontend site
I created the form like contact form to upload file and other details. urls.py from django.contrib import admin from django.urls import path from eSangrah import views urlpatterns = [ path("xerox", views.xerox, name='xerox'), views.py from django.shortcuts import render, redirect from .models import Xerox from datetime import datetime def xerox(request): if request.method=='POST': name=request.POST['name'] phone=request.POST['phone'] desc=request.POST.get('desc') file=request.POST['file'] xeroxs = Xerox.objects.create(name=name, phone=phone, desc=desc, file=file, date=datetime.now()) xeroxs.save() return redirect("/xerox") return render(request, 'xerox.html') models.py from django.db import models class Xerox(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=13) desc = models.TextField() file = models.FileField() date = models.DateTimeField() def __str__(self): return self.name admin.py from django.contrib import admin from .models import Xerox admin.site.register(Xerox) enter image description here If I click on the uploaded file . I get below error... enter image description here