Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: Using dictionaries as values for models.Choices
I'm trying to save a frequency to the database, which consists of an amount (e.g. 2) and a unit (e.g. months). The user must be given a choice, too. The idea is to pass this to a class that can use this info to calculate frequency (similar to, but not quite timedelta, however this is beyond the scope of this question). I thought it would be neat if I could save this information as a dict into a JSONField, and when retrieving it programmatically, I could pass it straight onto my CustomFrequencyClass in charge of the calculations. The error I invariably get is TypeError: unhashable type: 'dict'. Or, if I pass the values as tuples, it'll tell me (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. class CustomFrequencyClass: def __init__(self, *args, **kwargs): pass class Report(models.Model): class ReportFrequency(CustomFrequencyClass, models.Choices): DAILY = {"days": 1}, "Daily" WEEKLY = {"days": 7}, "Weekly" frequency = models.JSONField(choices=ReportFrequency.choices, default=ReportFrequency.DAILY) -
Real time messagin in django using channels
I am trying to create a Group chat functionality, but my webscoket connection is getting established but messages are sended but not received I have attached my code below please review and let me know solution, I will be very thankful consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.group_id = self.scope['url_route']['kwargs']['group_id'] self.group_name = f'chat_{self.group_id}' # Join group self.accept() self.channel_layer.group_add( self.group_name, self.channel_name ) def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.group_name, self.channel_name ) def receive(self, text_data): try: text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group self.channel_layer.group_send( self.group_name, { 'type': 'chat_message', 'message': message, } ) except json.JSONDecodeError: self.send(text_data=json.dumps({ 'error': 'Invalid JSON format.' })) except Exception as e: self.send(text_data=json.dumps({ 'error': str(e) })) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path('ws/(?P<group_id>\w+)/', consumers.ChatConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) asgi.py import os import django from django.conf import settings from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from all_pages.routing import websocket_urlpatterns as … -
Rest API calling issue
I am creating an Rest API which can access the endpoint API in my API i will post some data in endpoint API and that endpoint API will return some json format data , eventually that endpoint API is accepting my post data but that endpoint API is returning json format data i tried many time to debug the code and endpoint API link also but that didn't work -
Doesn't load the homepage for one group of users (Django)
I need to make a website for parents, teachers and admins to use. They all have different homepages, so I redirect them to their respective homepage by checking their group. Admins and teachers get redirected to the correct homepage, but for parent users, it just loads back the login page. Here's the code in my views.py for the redirection to the correct homepage def login(request): """Renders the login page.""" assert isinstance(request, HttpRequest) if request.user.is_authenticated: if request.user.groups.filter(name='admin').exists(): return redirect('admin_homepage') elif request.user.groups.filter(name='teacher').exists(): return redirect('teachers_home') elif request.user.groups.filter(name='parent').exists(): return redirect('parents_home') else: return render( request, 'app/login.html', { 'title':'Login', 'year': datetime.now().year, } ) And here are the related paths from the urls.py file urlpatterns = [ re_path(r'^homepage$', views.admin_homepage, name='admin_homepage'), re_path(r'^teachers_home$', views.teachers_home, name='teachers_home'), re_path(r'^parents_home$', views.parents_home, name='parents_home'), ] And if this can help, here's the parents_home.html file {% extends "app/parent/parent_layout.html" %} {% block content %} <title>{{ title }} - PTA Homepage</title> {% load static %} <div class="jumbotron2"> <h1><center>Parents - Teachers Association</center></h1> </div> <div class="vertical-center"> <div> <h2><center>Welcome to school's Parent - Teacher Management!</center></h2> </div> <div> <h3><center>What would you like to do today?</center></h3> </div> <div class="container2"> <center><button><a href="{% url 'dependanceMngt' %}">Dependance Management</a></button> <button><a href="{% url 'complaint' %}">Complaint</a></button> <button><a href="{% url 'eventMngt' %}">View Event</a></button> <button><a href="{% url 'viewAnnouncement' %}"> View Announcement … -
group_send() in Django channels
When ever a channel is created I'm adding it in a group. The issue is server sends the message to the latest channel in the group only rather than broadcasting it to the whole group. If I've two channels in my group the message will be sent to the latest in the group, twice. Help me debug. ` from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer from .models import Chat, Room from asgiref.sync import async_to_sync,sync_to_async class MyAsyncWebsocketConsumer(AsyncWebsocketConsumer): async def connect(self): print('connected...') self.group_name = self.scope['url_route']['kwargs']['group_name'] await self.channel_layer.group_add(self.group_name, self.channel_name) # Get old chats from database chat = await sync_to_async(Chat.objects.get)(room = await sync_to_async(Room.objects.get)(room_name = self.group_name)) await self.accept() # Show old chats await self.send(text_data=chat.chat) async def disconnect(self, code): print('disconnected....') await self.channel_layer.group_discard(self.group_name, self.channel_name) async def receive(self, text_data=None, bytes_data=None): print('Server sending messages...') # if user is authenticated save chat in database if self.scope['user'].is_authenticated: print('User is authenticated') prev_chat = await sync_to_async(Chat.objects.get)(room = await sync_to_async(Room.objects.get)(room_name = self.group_name)) new_chat = prev_chat.chat + '\n' + text_data prev_chat.chat = new_chat await sync_to_async(prev_chat.save)() # Saved # Broadcasts await self.channel_layer.group_send( self.group_name, { "type": "chat.message", "message": text_data, } ) else: print('User is not authenticated') async def chat_message(self, event): # Send a message down to the client print('Sending actual message...',event["message"]) await self.send(event["message"]) # print(self.channel_name) ` -
Getting a value from dropdown buttons to use later
I'm making a Django app that has 3 dropdown buttons Select host, select Filepath and Select Alert. I need to get back the selected values to use them later when running a InfluxDB script. I'm new to Django and I'm having a lot of problems with this. This is my index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Run Script</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="{% static 'script.js' %}"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> </head> <body> <h2>Run Script</h2> <div class="container"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-md-4"> <label for="host_select">Select Host:</label> <select id="host_select" name="host_select" class="form-control"> <option value="">Select...</option> {% for x in hosts %} <option value="{{ x.host }}">{{ x.host }}</option> {% endfor %} </select> </div> <div class="col-md-4"> <label for="filepath_select">Select Filepath:</label> <select id="filepath_select" name="filepath_select" class="form-control" > <option value="">Select...</option> {% for x in filepaths %} <option value="{{ x.filepath }}">{{ x.filepath }}</option> {% endfor %} </select> </div> <div class="col-md-4"> <label for="alert_select">Select Alert:</label> <select id="alert_select" name="alert_select" class="form-control"> <option value="">Select...</option> {% for x in alerts %} <option value="{{ x.alert_name }}">{{ x.alert_name }}</option> {% endfor %} </select> </div> </div> </form> <br /> <button type="button" id="run_button" class="btn btn-primary">Run</button> </div> </body> </html> and my views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse … -
Function call not working even though proper arguments are passed
let's say I have 2 files - file1 and file 2 - File 2 has a celery method - @async_worker.task(ignore_result=True, queue="data_path") def publish_msg_from_lock_async(mac: str, data: bytes, gateway_euid: str, req_id=None): try: vostio_log.info("here - ", extra=_log_token_dict) addr = mac payload = data vostio_log.info("addr {} - payload {} ".format(addr, payload), extra=_log_token_dict) device_id = VOSTIO_CLIENT_ID cert = VOSTIO_CERT_CRT key = VOSTIO_CERT_KEY ca = VOSTIO_CERT_CA host = VOSTIO_URL port = int(VOSTIO_PORT) from .sdk import VostioSDK n = VostioSDK(device_id, cert, key, ca, host, port) n.publish_msg_from_lock(addr, unhexlify(payload), gateway_euid) except Exception as e: return False This is being called in file1 like this - publish_msg_from_lock_async.apply_async(args=(addr, payload, gateway_euid)) publish_msg_from_lock method is also defined in file1 like this - def publish_msg_from_lock(self, mac: str, data: bytes, gateway_euid: str): vostio_log.info("Publishing message from lock ", extra=_log_token_dict) payload = json.dumps([{ 'id': f'{uuid.uuid4()}', 'addr': mac, 'data': b64encode(data).decode(), }]) topic = f'net/{self.id}/gw/{gateway_euid}/lock/up' self._publish(topic, payload) So if you see, file2 method has a log in starting of it, which is not coming, so the invoking is not happening. Can you please help. -
Using legacy database with masterdata in django
I have a database that is used in another project containing let's say info about employees. I need to use this info in my project: I have a user and I need to set his job title (as a ForeignKey). This job title is stored in the legacy db. I configured my project to work with multiple dbs and inspected my legacy db. Then I created a model that has a field job_title = models.ForeignKey(Employee, related_field='foo'). Legacy db can't be modified at all. As far as I understand there are two issues: If I can't modify legacy db, then I can't have related_field. Django doesn't support cross-db relations. What is the proper way to deal with two dbs? P.S. Django 5 Postgrsql DB -
Django throwing django.core.exceptions.SynchronousOnlyOperation with SyncPlaywright module
I'm currently working on a Django project where I need to scrape data from a website using Playwright. However, I'm encountering an issue due to the asynchronous nature of Playwright conflicting with Django's synchronous request/response cycle although I am using the Playwright's SYNC api. def extract_fbvideo_from_url(url, mp4_filename): playwright = sync_playwright().start() browser = playwright.chromium.launch(headless=True, channel="msedge") page = browser.new_page() page.goto(url) page_source = page.content() base_url = extract_url_from_source(page_source) response= requests.get(base_url, headers=headers) if response.status_code == 200: # filename= f"media/{uuid4().__str__()}.mp4" with open(mp4_filename, "wb") as f: f.write( response.content ) return mp4_filename print(f"Couldn't get fb video: [{url}]") return None The response is sent successfully as required but I am getting following error afterwords: Traceback (most recent call last): File "/usr/lib/python3.10/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.10/wsgiref/handlers.py", line 196, in finish_response self.close() File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/core/servers/basehttp.py", line 118, in close super().close() File "/usr/lib/python3.10/wsgiref/simple_server.py", line 38, in close SimpleHandler.close(self) File "/usr/lib/python3.10/wsgiref/handlers.py", line 335, in close self.result.close() File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/http/response.py", line 292, in close signals.request_finished.send(sender=self._handler_class) File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/db/__init__.py", line 38, in close_old_connections conn.close_if_unusable_or_obsolete() File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 510, in close_if_unusable_or_obsolete if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']: File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 389, in get_autocommit self.ensure_connection() File "/home/ubuntu/Saas_transcription/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 31, in inner … -
Can't configure MIDDLEWARE for Auditlog actor_id in Django
The documentation says that to automatically take the actor_id, I need to install a piece of auditlog.middleware.AuditlogMiddleware code in MIDDLEWARE. I did just that but nothing worked, I still can’t write who changed it MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'auditlog.middleware.AuditlogMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUDITLOG_INCLUDE_ALL_MODELS = True Other functions work correctly and without failures -
Nginx serves images but not css for django app
I use Django/Gunicorn/Nginx stack for my small webapp. I managed to put the app to production except that my app shows static images correctly but does not find the css file. My static resources like images, css, js were collected by python manage.py collectstatic outside of the project folder, to a folder accessible by Nginx: /var/www/example.com/html/static/. The content of the folder: ` ├── admin │ ├── css │ │ ├── autocomplete.css │ │ ├── .... │ ├── img │ │ ├── calendar-icons.svg │ │ ├── .... │ └── js │ ├── SelectBox.js │ ├── .... ├── booking │ ├── css │ │ └── style.css │ ├── img │ │ ├── andromeda.webp │ │ ├── .... ├── img │ └── favicon_16.ico └── ksa ..... ` My index page refers to images and css in the booking app. Here are two examples: <!--It is located in the head section--> <link rel="stylesheet" href="{% static 'booking/css/style.css' %}"> <!--It is located in the body section--> <img src="{% static 'booking/img/andromeda.webp' %}" alt=""> As you can see the references are following the same structure and consistent with the real folder structure. That's why it is weird that images return 200 status code while css returns 404. When … -
AppData\Local\Programs\Python\Python310\python.exe: can't open file 'F:\\py_project\\Django\\manage.py': [Errno 2] No such file or directory
AppData\Local\Programs\Python\Python310\python.exe: can't open file 'F:\py_project\Django\manage.py': [Errno 2] No such file or directory AppData\Local\Programs\Python\Python310\python.exe: can't open file 'F:\\py_project\\Django\\manage.py': [Errno 2] No such file or directory I don't know if that directory exist in file system. -
Django field look up __date is not returning objects
Why field lookup __date and __month are not returning any objects? class MembershipPlanSubscription(TimeStampBaseModel): user = models.ForeignKey(to=User, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() In [3]: objects = MembershipPlanSubscription.objects.all() In [4]: for object in objects: ...: print(object.end_date) ...: 2024-01-22 13:59:17.110148+00:00 2024-01-22 14:15:11.589769+00:00 2024-12-22 14:18:38.624196+00:00 2024-01-22 14:26:10.841796+00:00 2024-01-22 16:36:57.632614+00:00 2024-01-22 19:07:11.450086+00:00 2024-12-24 05:14:35.206241+00:00 2024-03-29 10:33:52.058009+00:00 2024-03-29 10:34:03.927215+00:00 2024-04-04 02:44:18.295650+00:00 2024-02-06 21:03:26.650677+00:00 2024-02-07 14:32:00.987613+00:00 2024-02-08 04:54:32.838352+00:00 2024-04-17 20:49:07.252812+00:00 2024-04-21 14:17:38.210087+00:00 2024-04-26 05:10:26.413481+00:00 2025-01-28 11:01:15.567712+00:00 2024-03-03 20:51:27.211525+00:00 2024-03-04 17:54:18.230713+00:00 2024-03-05 05:42:49.367263+00:00 2024-03-06 16:58:31.119124+00:00 2025-02-07 15:13:42.036329+00:00 2024-03-08 15:00:09.944520+00:00 2024-03-09 21:22:32.184259+00:00 2024-05-09 23:49:42.019238+00:00 2024-03-11 15:49:48.272387+00:00 In [5]: MembershipPlanSubscription.objects.filter(end_date__date = '2024-01-22') Out[5]: <QuerySet []> In [6]: MembershipPlanSubscription.objects.filter(end_date__date = datetime.date(2024, 1, 22)) Out[6]: <QuerySet []> In [8]: MembershipPlanSubscription.objects.filter(end_date__year='2024') Out[8]: <QuerySet [<MembershipPlanSubscription: MembershipPlanSubscription object (5)>, <MembershipPlanSubscription: MembershipPlanSubscription object (6)>, <MembershipPlanSubscription: MembershipPlanSubscription object (7)>, <MembershipPlanSubscription: MembershipPlanSubscription object (8)>, <MembershipPlanSubscription: MembershipPlanSubscription object (10)>, <MembershipPlanSubscription: MembershipPlanSubscription object (11)>, <MembershipPlanSubscription: MembershipPlanSubscription object (12)>, <MembershipPlanSubscription: MembershipPlanSubscription object (13)>, <MembershipPlanSubscription: MembershipPlanSubscription object (14)>, <MembershipPlanSubscription: MembershipPlanSubscription object (15)>, <MembershipPlanSubscription: MembershipPlanSubscription object (16)>, <MembershipPlanSubscription: MembershipPlanSubscription object (17)>, <MembershipPlanSubscription: MembershipPlanSubscription object (18)>, <MembershipPlanSubscription: MembershipPlanSubscription object (19)>, <MembershipPlanSubscription: MembershipPlanSubscription object (20)>, <MembershipPlanSubscription: MembershipPlanSubscription object (21)>, <MembershipPlanSubscription: MembershipPlanSubscription object (23)>, <MembershipPlanSubscription: MembershipPlanSubscription object (24)>, <MembershipPlanSubscription: MembershipPlanSubscription object (25)>, <MembershipPlanSubscription: MembershipPlanSubscription object (26)>, '...(remaining elements truncated)...']> In [9]: MembershipPlanSubscription.objects.filter(end_date__month='02') Out[9]: <QuerySet … -
CSRF Verification Failing
For my register and login views, I get this error CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. when I try accessing the endpoints. I can avoid this by adding a csrf_exempt decorator, but I'm worried about the security implications behind making a POST request csrf-exempt. My register endpoint specifically will write a verification code to my database (which the user has to enter to verify their email). Is there any way around this? I'm confused since to get a csrf token, I have to first call login(), but how can I access the login endpoint without a csrf token? -
Relationship serialiser Django rest framework
my serializers: class ProductVariantSerializer(serializers.ModelSerializer): value = serializers.CharField(source="option.name", read_only=True) class Meta: model = ProductVariant fields = ['id', 'value', 'price',] class ProductSerializer(serializers.ModelSerializer): variants = ProductVariantSerializer(source="product", many=True, read_only=True) class Meta: model = Product fields = "__all__" my result: enter image description here -
virtual environment name problem in django
I wanted to start Virtual environment again after closing it before but by mistake i wrote my project name(the projectname which we create in django after installing django with using django-admin startproject) instead of virtual environment name that i've created. I wrote this - py -m venv schoolMS and Was expecting this - py -m venv myschool and now terminal showing error - Error: [Errno 13] Permission denied: 'C:\Users\DELL\Desktop\My Study\Sem 6\Project\myschool\Scripts\python.exe' like this how can i solve the problem? -
Django pgtrigger class meta giving nameerror
NameError: name 'triggers' is not defined. Did you mean: 'pgtrigger'? hi , i am trying to implement postgress trigger in django for that i am using django-pgtrigger i am learning to implement it from the following doc https://django-pgtrigger.readthedocs.io/en/4.9.0/#quick-start but i am facing problem using the quickstart code my code from django.db import models import pgtrigger # Make sure you import the necessary module class ProtectedModel(models.Model): """Active object cannot be deleted!""" is_active = models.BooleanField(default=True) class Meta: triggers = [ pgtrigger.Protect( name='protect_deletes', operation=pgtrigger.Delete, condition=pgtrigger.Q(old__is_active=True) ) ] problem: NameError: name 'triggers' is not defined. Did you mean: 'pgtrigger'? can anyone help me to fix it ? ps. i am looking an easy way to implement database log functionality using trigger , if there any better way than this than please suggest , ty -
Django wrong environ TZ variable
i notice an issue, that environ.get('TZ') in django is different than system env TZ. In django it is always "America/Chicago", but if i try printenv TZ directly on server, or use python import os environ.get('TZ') it is different, correct, my env TZ that I expect to see in django. In django print all envs are same as system, except TZ. I misunderstand this =\ -
DisallowedHost at / Error: Invalid HTTP_HOST header: 'domain.com,domain.com' - How to Resolve?
I'm encountering an issue with my web application where I receive the following error message: "Invalid HTTP_HOST header: 'domain.com,domain.com'. The domain name provided is not valid according to RFC 1034/1035." This error occurs when I try to check the URL. I'm using Django for my web application. The server is running Ubuntu 22.04 with nginx as the web server and hosting is being managed using Gunicorn. I've already checked the domain configuration, and it seems to be correctly set up. However, I'm unsure why I'm getting this error and how to resolve it. Could someone please provide guidance on what might be causing this error and how to fix it? Any insights or suggestions would be greatly appreciated. -
error when connect to singlestore through django
I want to connect to singlestore through django with the following config: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'HOST': 'HOST', 'NAME': 'NAME', 'USER': 'root', 'PASSWORD' : '********', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', } } but I get this error: django.db.utils.DatabaseError: (1193, "1193 (HY000): Unknown system variable 'default_storage_engine'", 'HY000') django version is 4.7.2 and singlestore 6.8 what can I do? -
How to measure decibel value from a website?
I developed a website for conducting pure tone audiometry, which features frequencies at 500, 1000, 2000, and 4000Hz played separately in each ear. It includes a volume slider ranging from 0dB to 120dB. Users are prompted to click "next" when they can barely detect the tone, with the corresponding decibel value being saved upon clicking. My challenge lies in verifying the accuracy of the decibel values. How can I ensure that 5dB is indeed 5dB and 10dB is accurately represented? I am using Web Audio API. sample website I've heard about using an oscilloscope or spectrum analyzer for this purpose, but I wonder if there's software or a library available to assist with programming this feature. I purchased an inexpensive sound level meter and experimented with apps like Decibel X. However, accurate testing demands a soundproof environment, and the meter only detects a minimum of 30dB. Should we consider using an existing audiometer device to compare its "decibel" readings with those of our website? If so, what would be the approach? let audioContext; let oscillator; let gainNode; let isPlaying = false; let currentFrequencyIndex = 0; let frequencies = [500, 1000, 2000, 4000]; let currentEar = 'Left'; let frequencyDecibelData = []; … -
How can I stream rtsp (live video) in django app?
I tried to use StreamingHttpResponse in Django app for live rtsp streaming [https://docs.djangoproject.com/en/2.1/ref/request-response/#streaminghttpresponse-objects]. But du to documentation it's not correct. Does anyone have other solutions for this task? return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame")``` A new way to solve this problem? -
Python: Get multiple columns from database by filter
I want to get multiple columns from File table by filtering it by login_info. For example it will return 2 objects, but how can I handle it without this error get() returned more than one ParentMystudent -- it returned 2! views.py mystudent = ParentMystudent.objects.get(parent=request.session['login_info'].get('id')) query = File.objects.get(studentid=mystudent.mystudent_id) if query: for obj in query: student = Student.objects.get(registerid=obj.studentid_id) obj.student = student return render(request, 'file.html', {'query': query}) file.html {% for obj in query %} {% if obj in query.all %} <tr> <td><a href="#" class="fw-bold"></a>{{ forloop.counter }}</td> <td>{{ obj.soano }}</td> <td>{{ obj.student.lrn }}</td> <td><span src="{{ obj.file.url }}" target="_blank">{{ obj.student.lastname }}</span></td> </tr> {% endif %} {% endfor %} -
Django Switching sqlite3 to Postgres - User Unique Constraint Error
Was following this answer to switch my project database from sqlite3 to PostgreSQL, and encountered error when executing python manage.py loaddata datadump.json, my json file(google drive): django.db.utils.IntegrityError: Problem installing fixture 'C:\stuff\code\django-test01\django_project\datadump.json': Could not load auth.User(pk=1): duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. I aslso tried doing python manage.py migrate --run-syncdb, python manage.py dumpdata --exclude auth.permission --exclude contenttypes --natural-foreign --natural-primary > db.json and 'TRUNCATE django_content_type CASCADE;' in dbshell, but none of above did work. Am using Django's built-in User model('User' class from 'django.contrib.auth.models'). Tried to completely erase data from database and do it again, but for no avail. Tried answers(1, 2) from related questions, but they didn't work. What can I do to fix it and migrate my data from sqlite3 to Postgres? -
Django App not Deploying Correctly on Azure Web App Service
I've been following the steps outlined in the Azure documentation to deploy my Django app on an Azure Web App Service using local git deployment. After completing the steps, I can see the code and the virtual environment with the correct packages when I SSH into the web app. However, when I visit my site, it still loads the default Azure home page instead of my Django app. I attempted to troubleshoot by running python manage.py runserver in the SSH console, but I received the following error: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 12, 2024 - 01:20:11 Django version 4.1, using settings 'csvvalidator.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. It seems like the Django development server is running, but the port is already in use. I expected my Django app to be deployed following the tutorial, but it's not working as expected. Am I missing any additional steps or configurations to ensure that my Django app is properly deployed on the Azure Web App Service? Any guidance or suggestions would be greatly appreciated. Thanks!