Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django Logout Get method failed when attempting Post method
I am trying to build a simple login-logout mechanism with Django. The login is already working fine. Below are the relevant code snippets: project_name/main/urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ # ... path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), ] project_name/templates/registration/logged_out.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Logged out</title> </head> <body> <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <p>Logged out!</p> <a href="{% url 'login' %}">Click here to login again.</a> </form> </body> </html> I have a href element on project_name/templates/profile.html that goes to logout: <p><a href="{% url 'logout' %}">Logout</a></p> But when I click it, I get the following error: Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/ I'm quite confused because the method attribute in the form element in logged_out.html is clearly "post". I looked at previous questions and none of them have this exact issue. Could anyone kindly tell me what is going on? Thanks in advance. - 
        
Table & Django Templates
Consider the following models: Animal --> Pet (with foreign key to Animal) Both objects have an integer field - ordinal - that is supposed to control the order of their listing. Say we have 2 instantiations of animals: Dog, Cat And we have 5 Pets: Dog --> Fido, Scooter, Ralphie Cat --> Murphy, Winston Typically, I would represent them with unordered lists. But let's say we would want to pass in context for an HTML table instead... Dog...................Cat -------------- ------------------ Fido...................Murphy Scooter............Winston Ralphie The Animal models would be represented in the table headers, and their children of the Pet class instantiations would fall under them in the table rows. From there, the end-user would click on a hyperlink with the object name to drill down to that pet, with a slugfield providing the argument for the url. What this means is, I only need the Animal name for the table headers, but I need both name and slug for their Pets. Having all of that to consider, there is one more consideration... Note that there is an empty cell for cats, since there's one less cat. How would I create the context I would pass to the template, without (nothing) … - 
        
Getting BAD REQUEST, while fetching address it's returning empty string
views.py: from django.shortcuts import render from geopy.geocoders import Nominatim from django.http import JsonResponse Create your views here. def single_address(request): if request.method == 'POST': #print(request) address = request.POST.get('address','') #print(type(address)) if address: # Initialize Nominatim geocoder geolocator = Nominatim(user_agent="my_geocoder") try: # Geocode the address location = geolocator.geocode(address) if location: # Extract latitude and longitude latitude = location.latitude longitude = location.longitude return JsonResponse({'latitude': latitude, 'longitude': longitude}) else: return JsonResponse({'error': 'Geocoding failed for the address'}, status=500) except Exception as e: return JsonResponse({'error': f'Error: {str(e)}'}, status=500) else: return JsonResponse({'error': 'Address not provided'}, status=400) else: # Render the HTML template for the form return render(request, 'address/single_address.html') single_address.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get Coordinates for Single Address</title> </head> <body> <h1>Get Coordinates for Single Address</h1> <form id="addressForm"> {% csrf_token %} <label for="address">Enter Address:</label> <input type="text" id="address" name="address" required> <button type="submit">Get Coordinates</button> </form> <div id="response"></div> <script> document.getElementById('addressForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent form submission var address = document.getElementById('address').value; // Make an AJAX request to the view fetch("{% url 'single_address' %}", { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'address': address }) }) .then(response => response.json()) .then(data => { // Display the response document.getElementById('response').innerText = JSON.stringify(data, null, … - 
        
Deploying to Ec2 Instance Aws error showing "Disallowed Host"
Hey guys im getting an error when deploying my django project to Aws Ec2. In my allowed hosts i put it open to allow any website to open it ["*"] . Still showed the error. Then i keyed in the address of the public Dns provided by ec2 but still the error type here In my allowed hosts i put it open to allow any website to open it ["*"] . Still showed the error. Then i keyed in the address of the public Dns provided by ec2 but still the error - 
        
Adding forms when using Django modelformset_factory
I start using Django's modelformset_factory. I want to use it to add a number of records to my Shift model. what I simply want is to have 3 buttons (maybe 4) Add empty form Copy last form (when only a few things need to be changed) Save (Optional) Delete record I thought this was all intended to be part of the modelformset_factory but I learned I need javascript to do this. Here is my attempt to get this done: <script> $(document).ready(function () { $('.js-example-basic-single').select2(); }); </script> <script> $('#add-more-btn').click(function () { const newForm = $('#formset-container').children().last().clone(); // Increment indices and update IDs/names in new form newForm.find('input, select').each(function () { const name = $(this).attr('name'); if (name) { const formIndex = parseInt(name.match(/form-\d+$/)[0].match(/\d+$/)[0]); const newIndex = formIndex + 1; $(this).attr('name', name.replace(/form-\d+$/, `form-${newIndex}`)); $(this).attr('id', name.replace(/form-\d+$/, `form-${newIndex}`)); } }); // Re-initialize Select2 newForm.find('.js-example-basic-single').select2(); newForm.appendTo('#formset-container'); }); </script> {% extends 'base.html' %} {% load static %} {% block additional_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/form.css' %}"> {% endblock %} {% block content %} <form method="post" id="formset"> {% csrf_token %} {{ formset.management_form }} <div id="formset-container"> {% for form in formset %} <div class="formset-form"> {{ form.as_p }} </div> {% endfor %} </div> <button type="button" id="add-more-btn">Add Shift</button> <button type="submit">Save shifts</button> </form> … - 
        
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?