Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a custom RegistrationForm using django-registration in Django 5.0.2 with Django Registration 3.4
I admit I'm new to Django but I've been banging my head against the wall with this problem all day. I've created a new application and inherited classes from django_registration, but it seems my form data is never saved. My fields show up and are accessible on the front end as well as the administration area, but user registration never seems to happen and I don't get an error. (It is working fine with standard django-registration but I want to expand it and plan for the future.) forms.py from django_registration.forms import RegistrationForm from authentication.models import MyCustomUser from django import forms class MyCustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = MyCustomUser #fields = "__all__" fields = ['username', 'email', 'first_name', 'last_name', 'profile_photo', 'password1', 'password2'] models.py from django.contrib.auth.models import AbstractUser from django.db import models from django import forms class MyCustomUser(AbstractUser): ROLE_CHOICES = ( ('APPLICANT', 'Applicant'), ('EMPLOYEE', 'Employee'), ('ADMIN', 'Admin'), (None, 'None') ) role = models.CharField(max_length=30, choices=ROLE_CHOICES) profile_photo = models.ImageField() #username = forms.CharField(max_length = 100) #this is already handled for us in AbstractUser #email = forms.EmailField(max_length = 100) #this is already handled for us in AbstractUser #password1 = forms.CharField(widget = forms.PasswordInput(), max_length = 100) #this is already handled for us in AbstractUser #password2 = forms.CharField(widget = forms.PasswordInput(), … -
ajax real-time page refresh
Well, in general, I'm doing a small project on django and I decided to implement a convenient search for any parameter from my form. all js was written to me by chatgpt and I don't understand it at all at all, and in general I'm working with "search" for the first time. also, what worries me now is that it is actually being searched for, but very crookedly. everything is shaking and the header is duplicated under the search. I need a dynamic page update when searching for the number, VIN, sent_at, status fields. html {% block title %} Для крутых {% endblock %} {% block content %} <div class="container"> <div class="row mt-3"> <input type="search" id="search-input" name="q" class="form-control form-control-dark text-bg-dark" placeholder="Поиск..." aria-label="Поиск"> <div id="applications-list" class="mt-3"> {% for application in applications %} <div class="application-item"> <p><strong>Имя:</strong> {{ application.name }}</p> <p><strong>Номер телефона:</strong> {{ application.number }}</p> <p><strong>VIN номер машины:</strong> {{ application.VIN }}</p> <p><strong>Описание проблемы:</strong> {{ application.description }}</p> <img src="{{ application.image.url }}"> <p><strong>Отправлено:</strong> {{ application.sent_at }}</p> <p><strong>Статус:</strong> {{ application.status }}</p> <br> </div> {% endfor %} </div> {% include 'includes/pagination.html' %} </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { function searchAndUpdate() { let searchQuery = $('#search-input').val(); $.ajax({ url: window.location.href, data: { q: searchQuery }, success: function(data) { … -
IntegrityError at /password-manager/user/17/add_password/
I'm trying to implement a password-manager app for storing passwords. Here I'm trying to add a password for the current user. I'm getting this error: IntegrityError at /password-manager/user/17/add_password/ FOREIGN KEY constraint failed This is the view: def user_add_password(request,id): obj = get_object_or_404(UserModel, id=id) form = PasswordForm(request.POST or None, user=obj) if form.is_valid(): form.instance.user = obj form.save() return redirect(reverse('password:user_home_page', kwargs={'id': obj.id})) context = { 'form': form, 'object': obj } return render(request, 'add_password.html', context) This is the form: class PasswordForm(forms.ModelForm): class Meta: model = Password fields = ['user', 'platform', 'password'] widgets = { 'user': forms.HiddenInput(), } def __init__(self, *args, **kwargs): # Get the user from the initial data or set it to None user = kwargs.pop('user', None) print(user,'@@@@@@@@@@@@@@@@@@@@22') # Call the parent constructor super(PasswordForm, self).__init__(*args, **kwargs) # Set the initial value for the user field if user: self.fields['user'].initial = user This are the Models: secret_key = settings.SECRET_KEY f = settings.FERNET_INSTANCE salt = settings.SALT # Create your models here. class UserModel(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) def get_absolute_url(self): return reverse('password:user_detail', kwargs={'id': self.id}) def save(self, *args, **kwargs): self.password = bcrypt.hashpw(self.password.encode('utf-8'), salt).decode('utf-8') super().save(*args, **kwargs) class Platform(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name @staticmethod def initialize_platforms(): Platform.objects.all().delete() platforms= ['Facebook' , 'Instagram' , 'Twitter' ,'Google' … -
Why my deploy to railway of a django project is getting a error?
I am trying to do a deploy of a django project do railway and I am getting this error: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: --log-file-- I don't know why is showing the argument --log-file--, because in my file is in the correct form --log-file - Like this: web: gunicorn agenda.wsgi --log-file - If someone have this error too, could help me? I am expecting the railway deploy my website -
django order_by("datetime") does not work
I am trying to get all objects off "Chat" distinct by the fields phone_number (CharField) and agent (ForeignKey) and order by datetime DateTimeUTCField(default=datetime.now) chats = self.get_queryset().order_by('phone_number', "agent","-datetime").distinct("phone_number", "agent") for chat in chats: print(chat.datetime) but when I see the order of the chats, the chats are not sorted by datetime 2024-02-12 14:12:29.352192 2024-02-12 16:14:36.196964 2024-02-12 14:20:26.696088 2024-02-12 14:16:36.225550 2024-02-12 17:25:45.896345 2024-02-12 17:35:58.424937 2024-02-12 15:07:23.808822 2024-02-12 16:14:37.775311 2024-02-12 14:19:28.939897 2024-02-12 16:14:34.493954 2024-02-12 16:41:08.697777 Why? I think is because i have also order_by phone_number and agent , but if I remove then , django raises SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("lolo_agents_chat"."phone_number", "lolo... -
AttributeError: Got AttributeError when attempting to get a value for field `value` on serializer
I am trying to serialize the data in my ecommerce project with DRF. My db design is such that I have a Product which can have multiple ProductVariant and each ProductVariant can have multiple ProductVariantProperty associated with it. This is my models.py class ProductVariantProperty(models.Model): name = models.CharField(max_length = 255, null = True, blank = True) class ProductVariantPropertyValue(models.Model): value = models.CharField(max_length = 255, null = True, blank = True) property = models.ForeignKey( ProductVariantProperty, on_delete = models.CASCADE, null = True, blank = True, related_name = 'product_variant_property_values' ) class Product(models.Model): name = models.CharField(max_length = 255, unique = True, null = False, blank = False) ... class ProductVariant(models.Model): product = models.ForeignKey( Product, on_delete = models.CASCADE, null = False, blank = False, related_name = 'product_variants' ) name = models.CharField(max_length = 255, unique = True, null = False, blank = False) ... properties = models.ManyToManyField(ProductVariantProperty, blank = True, related_name = 'product_variants') This is my request body { "name": "Product 1", ... "product_variants": [ { "name": "Example Variant 1", ... "properties": [ { "name": "color", "value": "blue" }, { "name": "size", "value": "large" } ] }, {...} ] } This is the error i got when i tried to serialize. AttributeError: Got AttributeError when attempting to get … -
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?