Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid Graphene sorting an OrderedDict on query response? (Python, Django)
I am trying to return a dict of OrderedDicts from a Graphene endpoint in a Django application, by using the GenericScalar type field. The OrderedDicts are sorted based on value, but the API seems to re-sort the dicts by key. The OrderedDicts items format is: { id : [name, amount] } Example of one of the OrderedDicts that I send: { 'foods': { 3: ['apple', 5], 1: ['banana', 7], 2: ['carrot', 3] }, 'animals': { 5: ['cat', 3], 3: ['dog', 10], 1: ['pig', 5], } } What is received in the endpoint response: { 'foods': { 1: ['banana', 7], 2: ['carrot', 3], 3: ['apple', 5], }, 'animals': { 1: ['pig', 5], 3: ['dog', 10], 5: ['cat', 3], } } I am specifically using OrderedDicts because the order is important, but I have not found a way of avoiding Graphene to re-sort the OrderedDicts by key. This is the how the ObjectType and Query are declared, althought is is nothing out of the ordinary. class DashboardType(g.ObjectType): data = GenericScalar() class Query(object): dashboard = Field(DashboardDataType, id=ID(), date=Date()) def resolve_dashboard(self, info, **kwargs): data = function_to_get_the_data(kwargs) # up until this point the data is still sorted correctly return data The data is sorted as … -
Booking Cycle with Django
I have an app where the user books a session and then pay it using payment service provider (like Fawry or Paymob which are middle-east based companies). the way this is done is when the user books a session or multiple sessions a code is generated and it will be available for say 30 mins. My Question is : should I declare the sessions that the user is going to pay for as booked so when another user fetches the sessions they will not be available to be booked? and if so what happens if the user decided not to pay for the sessions, how would I know? and if I can know and return them back to unbooked status what if the other user that wanted them didn't check for these sessions again? OR should I make them available until the user pay for them then remove them from the available sessions, but then what if two users booked the same session -as it's not yet been removed when one user booked it-, the generated code that they are going to use has an amount of money to be paid it will not check if the session that the … -
How to Merge Byte Files Together in Python
I am running into a situation where I need to generate multiple filled PDF forms, I have the data filled out and the 'bytes' file is accessible, but when I attempt to combine the 2 files in their byte representation, nothing happens, the file is overridden and the original is the only thing shown. What am I doing wrong, this seems like it should be easy. # don't worry about these, they are filled PDFs in byte form, this works as expected. pdf1 = PDFFormManager.fill_with_jinja(file=template, data=data) pdf2 = PDFFormManager.fill_with_jinja(file=template, data={}) # here is the issue print(len(pdf1), len(pdf2)) # 177354 177354 print(type(pdf1), type(pdf2)) # <class 'bytes'> <class 'bytes'> print(len(pdf1+ pdf2)) # 354708 # when I return this, I only get the single pdf, not the concatenated one response = HttpResponse(pdf1+pdf2, content_type=f"application/pdf") -
How to translate simplejwt error (django rest framework)?
What is the best way to translate the error: "No active account found with the given credentials" coming from: from rest_framework_simplejwt.views import TokenObtainPairView ... urlpatterns = [ path('token/', TokenObtainPairView.as_view()), I use React on the frontend and Django and Django Rest Framework on the backend. I changed django settings to: LANGUAGE_CODE = 'pl' but this apparently didn't change the simplejwt error language. -
Django web development pdf [closed]
I want all the pdf to be displayed on the webpage from the database and one can see it from there… The display part is done but whenever i click on a pdf the page loads and gets redirected to the same page and pdf doesn’t open… what should I do? I tried everything but it won’t solve -
I am getting error for Deploying django project on vercel can anyone help me with this
enter image description here i am getting error like this I have tried so many ways to fix it but it didn't help. I think the error must be in selecting the framework preset for Django on Vercel while deploying, I think so. I have selected "OTHER" for Django deployment as suggested on youtube tutorials. -
I am getting raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
My settings.py looks like this and I have created a db with name student in mysql. Despite having installed mysqlclient latest version I am getting this error. I tried with using other database setup but still got similar error. """ Django settings for studentReportCard project. Generated by 'django-admin startproject' using Django 4.2.3. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%38#(h6gd4$$2%n7+-3v3#-n)mcaobie=)1o&f()+&8m!+oq)!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'report_card', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'studentReportCard.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'studentReportCard.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'NAME': 'student', … -
Django crispy_forms using
I have been using crispy_forms for my form on django project. But While Project is running. A problem A problem appears suddenly. how can I solve this problem on my project ? can you help me ? I have to go on this project very faster [[[enter image description here](https://i.stack.imgur.com/x8kr2.png)](https://i.stack.imgur.com/UF8XI.png)](https://i.stack.imgur.com/fDG6k.png) -
Im trying to make a Instagram reel downloader and keep getting this error Expecting "property name enclosed in double quotes: line 1 column 2 (char 1)
Im using django to create a instagram reel downloader but it keeps giving me json errors My code: from django.shortcuts import render , redirect from instascrape import * import json import time # Create your views here. def index(request): if request.method == "GET": return render(request, "index.html") else: if request.POST['url']: google_reel = Reel("https://www.instagram.com/reel/CumvX9VgNQt/?utm_source=ig_web_copy_link&igshid=MzRlODBiNWFlZA==") google_reel.scrape() google_reel.Download(fp = "{path\filename.mp4}") else: return render(request, "index.html", { "error": "Invalid url" }) return redirect("/") The error im getting is "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" im thinking it is a python package problem the one im using is instascrape (https://github.com/chris-greening/instascrape) -
How to send message through django-channels from asyncio loop with add_reader
I am trying to listen for notifications from postgres database and send message through django-channels on each row insertion, for that I want to use asyncio loop, where I am adding reader for connection. However, I am receiving following error on attempt to use async_to_sync: RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Here is my code: import asyncio import logging import channels.layers from asgiref.sync import async_to_sync from django.conf import settings from django.core.management.base import BaseCommand from django.db import connections channel_layer = channels.layers.get_channel_layer() logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): conns = [(connections[db].cursor().connection, db) for db in settings.DATABASES] loop = asyncio.get_event_loop() for conn, db in conns: conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute("LISTEN event_changed;") loop.add_reader(conn, partial(self.handle_notify, conn=conn, db=db)) logger.info("Starting runlistener loop.") loop.run_forever() def handle_notify(self, conn, db): conn.poll() for notify in conn.notifies: logger.debug(f"new event received on db {db}: {notify.payload}.") async_to_sync(channel_layer.group_send)( db, {"type": "on_new_event", "event": notify.payload} ) conn.notifies.clear() I can't use await in handle_notify since it is not async function and I couldn't find any way to use async function as a callback for add_reader. I've managed to implement this functionality without asyncio, by simply checking connection with select.select in … -
How can fix ' Error: No application module specified.' on DigitalOcean
I am getting ' Error: No application module specified. ' error while I'm trying to deploy my django project. After Successful Build, Digital Ocean is trying deploy it and raise this error after short time. Can you help me about this? Where should I change? settings.py >>> """ Django settings for djcrm project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv # .env dosyasını yükle load_dotenv() DEBUG = os.getenv('DEBUG') # SECRET_KEY'i al SECRET_KEY = os.getenv('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #third party apps 'crispy_forms', "crispy_tailwind", 'tailwind', #local apps 'leads', 'agents', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": … -
Query many to one backward relation Django
I have these 2 models: class User(models.Model): full_name = models.CharField(max_length=255) class WorkSchedule(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) day_of_week = models.IntegerField() start_time = models.TimeField() end_time = models.TimeField() Is it possible for me to use a single query here to get back something like this: { "id": 1, "full_name": "User name", "work_schedule": { { "day_of_week": 1, "start_time": 8:00, "end_time": 20:00 }, { "day_of_week": 2, "start_time": 8:00, "end_time": 20:00 } } } -
Form field not showing in tempate
after defining form field when I try to access in django template using {{form.Date_Joined}} not working class UserAdd(forms.ModelForm): class Meta: model=CompanyUsers fields= '__all__' exclude=['usrPsswd','usrId','usrCmpnyId','lstLogin','is_active','usrDOJ'] widgets={ 'Date_Joined':forms.DateInput(attrs={'type':'date'}), } The widget i've declare not showing <div class="order"> <!-- <div class="head" > --> <h4> ADD COMPANY</h4> <!-- </div> --> <table id="table-datas"> <form method="POST" action=""> {% csrf_token %} <tbody> <tr><td>Username</td><br><td>{{ form.usrNme}}</td></tr> <tr><td>First Name </td><br><td>{{ form.usrFNme}}</td></tr> <tr><td>Last Name </td><br><td>{{ form.usrLNme}}</td></tr> <tr><td>Date of join</td><br><td>{{form.Date_Joined}}</td></tr> <tr><td>Department</td><br><td>{{ form.usrDpt}}</td></tr> <tr><td>Email</td><br><td>{{ form.usrMail}}</td></tr> <tr><td><button type="submit">Register</button></td></tr> </form>``` so the Date Joined field shows nothing -
How to make table editable in django on the clientside
I am building this Django webapp, where I have data stored in the SQLite. And being fetched into a table in the client side. But I have this idea of patching the data from the table itself, just like Edit in grid view, of sharepoint list. Where If I click the toggle button 'editable mode', the all cells become editable and after making necessary changes, if click the toggle button again, the changes should be saved in the database as well. Below are the snippets of the project. views.py class EmployeeUpdateView(View): def patch(self, request, employee_id): data = json.loads(request.body) try: employee = Employee.objects.get(id=employee_id) for change in data: field_name = change['field_name'] field_value = change['field_value'] setattr(employee, field_name, field_value) employee.save() return JsonResponse({'success': True}) except Employee.DoesNotExist: return JsonResponse({'success': False, 'error': 'Employee not found'}) except Exception: return JsonResponse({'success': False, 'error': 'Error saving changes'}) this is url path path('update/<int:employee_id>/', EmployeeUpdateView.as_view(), name='update_employee'), this is the table template <tbody class="thead-light"> {% for employee in page_obj %} <tr style="font-size: 12px;"> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.name }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.phone }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.dob }}</td> <td {% if not employee.editable %}contenteditable="false"{% endif %}>{{ employee.doj }}</td> … -
Wagtail Image Chooser Template returns 404 http not found
When I deploy my wagtail django with nginx and I want to choose an image for a ForeignKeyField to wagtailimages.Image I get a HTTP 404 for <base-url>/cms/images/chooser/ although when I directly access the url it returns the correct json. Is this a nginx Problem or a wagtail / django problem? -
Convert PDF to PDF/A with python
I am working on a Python project and I need to convert a PDF file to PDF/A format programmatically. Ideally, I'm looking for a Python library or tool that supports PDF to PDF/A conversion and provides options to specify PDF/A compliance levels, such as PDF/A-1a or PDF/A-3b. Any example code or a step-by-step guide would be greatly appreciated. I have explored some libraries such as PyPDF2 and pikepdf, but I haven't found a straightforward way to achieve this. Can anyone provide guidance on how to convert a PDF file to PDF/A using Python? -
Django: Rest Framework (Serializer)
I'm new to using the django rest framework. I'm trying to understand how I can validate a field with the serializer based on the input from the user, for example: Serializer: from rest_framework import serializers VALID_REGION = 'region' def validate_region(value): if value != VALID_REGION: raise serializers.ValidationError('Invalid region, make sure region parameter is spelled correctly.') return value class RegionSerializer(serializers.Serializer): region = serializers.CharField(required=False, validators=[validate_region]) Here I want to validate that the region is spelled correctly. views.py def get(request, *args, **kwargs): serializer = RegionSerializer(data = request.data) if serializer.is_valid(): data = serializer.validated_data region = data.get('region', '') regions = region_lib.get_regions(region) return Response({"regions" : regions}, status=status.HTTP_200_OK) else: errors = serializer.errors return Response({"error" : errors}, status=status.HTTP_400_BAD_REQUEST) Here I pass 'regoin' misspelling it intentionally. { "regoin": "Test" } When I run serializer.is_valid() it returns true. Not sure what I'm missing. -
In Django, how to get the return of two functions in the same html page? Error: TypeError: kwargs argument must be a dict, but got function
In Django I have two functions contained in views.py. One is called def city_detail and the other is called def DemoView. Both return return render(request, 'app1/home.html', context). In url.py I would like to use both functions, but it seems I can only use 1 at a time. If I use only one of the two, then it works (only one of the two works). If I write in urlpatterns I write: path('home/', views.city_detail, views.DemoView, name='home'), path('home/', views.DemoView, name='home'), I get the error: raiseTypeError( TypeError: kwargs argument must be a dict, but got function. How can I use both functions in home? -
How to filter the model property value using custom filter in Django admin
I have the model with property and custom filter. Depending on the custom filter value, I need to update the _approved property value (not the model queryset) on the Django admin page. model.py class Model(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created') updated = models.DateTimeField(auto_now_add=False, auto_now=True, verbose_name='Updated') @property def _approved(self): return ModelRecordRelation.objects.filter(model_id=self.id, status='A').count() admin.py class TimeFrameFilter(SimpleListFilter): title = 'timeframe' parameter_name = 'timeframe' def lookups(self, request, model_admin): return [ ('Today', 'Today'), ('ThisWeek', 'This Week'), ] def queryset(self, request, queryset): return queryset.filter() class ModelAdmin(admin.ModelAdmin): list_display = ['created', 'updated'] class Meta: model = Model def approved(self, obj): return obj._approved approved.admin_order_field = 'approved' -
Unable to fetch data with axios from Django backend using relative path
I am currently developing a web application using React for my frontend and Django for my backend. The frontend and backend are running on separate local servers. I am trying to fetch some data from my Django backend using axios in my React application with the following code: const handleButtonClick = () => { setLoading(true); axios .get("/bucket-size/") .then((response) => { const size = response.data.bucketsize; const unit = response.data.unit; setOutput(size + " " + unit); }) .catch((error) => { console.error(error); }) .finally(() => { setLoading(false); }); }; The Django backend route looks like this: path('bucket-size/', BucketSize.as_view(), name='bucket-size'), Note -- i do not want to add a proxy to my package.json since the backend will be running on Docker and i want it to fetch relatively. Can anyone help? -
Generate IFCRoad via IFCOpenShell
I have this model class Tramif_PCI_agrup(models.Model): id = models.AutoField(primary_key=True) pci = models.FloatField(null=True) geom = models.LineStringField(geography=True, srid=4326, null=True) That i want to translate into an IFCRoad using the IFCOpenShell library to get a final IFC file with every Object with its geom and its PCI value. This is what i tried but it didnt work # Get all objects from the Tramif_PCI_agrup model tramif_pci_agrups = Tramif_PCI_agrup.objects.all() # Create a blank model ifc_file = ifcopenshell.file(schema='IFC4X3') # Create an IfcRoad entity road = ifc_file.create_entity("IfcRoad") road.Name = "Simple Road" # Fetch objects from the model and iterate over them for tramif_object in tramif_pci_agrups: # Extract geometry and PCI values from the model object geom = tramif_object.geom pci = tramif_object.pci # Convert the geometry to WKT format wkt_geom = geom.wkt # Create an IfcAlignment entity for each object alignment = ifc_file.create_entity("IfcAlignment") alignment.Name = f"Alignment {tramif_object.id}" alignment.Description = f"PCI: {pci}" # Create an IfcAlignmentCurve entity for the geometry curve = ifc_file.create_entity("IfcAlignmentCurve") curve.Axis = ifc_file.create_entity("IfcCurve") curve.Axis.Points = ifc_file.create_entity("IfcPointList") curve.Axis.Points.Coordinates = [(coord[0], coord[1], 0) for coord in GEOSGeometry(wkt_geom)] # Add the alignment curve to the alignment entity alignment.Representation = curve # Add the alignment entity to the road road.Representation = alignment # Write the IFC file ifc_file.write("/images/road_test.ifc") But … -
How to set env variables for django test in vscode
I would like to set env variable for django test in vscode. These env variables will be different from env variables to be used in django run server. -
TinyMCE is not working correctly in my django project
I have created a Django blog site where I can write blog posts both from the main site and the admin site. To compose my blog posts, I am using the TinyMCE editor. When I am in the admin site, I can successfully write and submit my blog posts using TinyMCE. However, when I attempt to write a blog post from the main site using TinyMCE, I encounter an issue. Although my submit button appears to be working correctly, it does not perform any action upon clicking it. Strangely, if I refresh the page and then click the submit button again, my blog post gets posted, and everything works fine from that point onward. Please tell me What is the mistake that I'm doing. This is my tiny.js file var script= document.createElement('script'); script.type='text/javascript'; script.src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload=function(){ tinymce.init({ selector: "#id_content", height:656, plugins: [ 'advlist autolink link image lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor … -
Gunicorn Fargate ELB healthcecks fail before auto scale
I have setup a django application using gunicorn server on ECS with Fargate backend. I have setup auto scaling based on both CPU and Memory utilisation. Fargate capacity: 2 vCPU and 4 GB RAM The problem is that whenever the load is high, even before the CPU utilisation is high, the ELB healthchecks are failing and as a result the task is getting deregistered and never leads to auto scaling. gunicorn is running with 2 workers and 4 threads. gunicorn <appname>.wsgi:application --workers 2 --threads 4 I'm trying to understand the reason for this and how to solve this issue. -
why for loop not working in django .Error in rendering html in django using for loop
i am writing code to get a carousal which consists of products using for loop in python But there is some isuue it is generating everthing but not generating my items inside carousal Things defined here: list_of_range=[[0, 1, 2], [3, 4]] Now my no of slides in carousal is generated pretty well but items in side each slide is not get generated Here's the code in index.html <div class="container mt-5" > <div id="carouselContainer" class="carousel slide" data-ride="carousel"> <div class="carousel-inner justify-content-center"> {% for i in list_of_range %} {% if i == list_of_range.0 %} <div class="carousel-item active"> {% else %} <div class="carousel-item "> {% endif %} <div class="row"> {% for d in list_of_range.i %} <div class="col-sm-3 col-md-3"> <div class="card" style="width: 18rem"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyRql003EXAw9EVs6V3koKd5wXbW0Lt-yJOA&usqp=CAU" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{products.0.product_name}}</h5> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} and the code in main.py is as follows : def index(request): all_products_list = Product.objects.all() n= len(all_products_list) nslides = n//3+ ceil((n/3)-n//3) print(nslides) prod_range_list = [] to_range = n for c in range(nslides): if to_range/3>=1: prod_range_list.append(list(range(c * …