Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't figure out how my Django React Create Form returns, 'Unsupported Media Type: /api/auctions/'
My Django REST API uploads an auction correctly (including the required images) when I make a post request in Postman. However, my React auctioncreateform.js file does not successfully create an auction and instead returns the error below: 'Unsupported Media Type: /api/auctions/'. THE FORM WORKS AS INTENDED when I remove the uploaded_images values/attributes from the project. The post request through the form shows an error when I include the uploaded_images field. console.log(values); in my auctioncreateform.js returns these: bestdeals: false car_specification: [12] (1) category: 1 duration: 7 make: 1 model: 1 name: "jhjh" overview: "<p>gfgfg</p>" reserveprice: 0 start_time: "2023-05-27T10:53" starting_price: 0 type: "SUV" uploaded_images: Array (1) 0 File {path: "BM945737_dec96f.jpeg", name: "BM945737_dec96f.jpeg", lastModified: 1684687221000, webkitRelativePath: "", size: 83369, …} Array Prototype year: "2012" Below is my auctioncreateform.js import React, { useState, useEffect } from "react"; import clsx from "clsx" import { Formik, Form, Field, ErrorMessage } from "formik" import { useSnackbar } from "notistack" import Alert from 'react-bootstrap/Alert'; import Container from 'react-bootstrap/Container'; import axios from "axios"; import FilesDropzone from "../../../../components/Files-Dropzone"; import { postAuctionAxios } from '../../../../services/AuctionService' import { YupAuctionValidation } from "./schema/YupAuctionValidation" import { AuctionDefaultValue } from "./schema/AuctionDefaultValue" import { useNavigate } from "react-router" const AuctionCreateForm = props => { .... return … -
Django Forms: Display MultipleChoiceField select options below its label
In my views.py file, I have a form with the following field: test_type = forms.MultipleChoiceField(label="Test Type:", choices=ALL_TEST_TYPES_OPTIONS, widget=forms.SelectMultiple(attrs={'size': '15'})) I'm rendering it in my associated .html template file by using {{form.as_p}} inside of the following <form> tag: <form method="POST" action=""> {% csrf_token %} {{response.status_code}} - {{response.reason}} {{page_errors}} {{form.as_p}} It displays as such: My goal, which I'm seeking suggestions on how to achieve, is to simply put the select options below the label ("Test Type:"), rather than the current formatting of the select options being to the right of this label. Perhaps there's a command to perform this styling within its definition (in views.py as I inserted above) along the lines of what I did for setting its size attribute to be 15. Or, if there's a way I could break up its rendering in the HTML file to insert a <br> (line break) between the label and select options. -
Django admin add popup not working with many-to-many attribute on itself
Im trying to use in django admin a simple model like this: class Model1(models.Model): value = models.CharField(max_length=100) valuem2m = models.ManyToManyField("Model1", related_name="model1", blank=True) When try to add values in admin, if I try to open more than 1 popup, it didn't open another window, only redirect to the next form. first emergent window When I save this gives me this error. pup_response.js:13 Uncaught TypeError: opener.dismissAddRelatedObjectPopup is not a function at popup_response.js:13:16 window broken This is because the autogenerated id of the add button is the same of the child add button. (add_id_valuem2m). DevTools id's There is a way to make this work? -
Using Django TestCase, how do I create a test that sends a post request to my view, with data and files for a modelform
I have browsed SO, google, and have not been able to find a solution that works, or at least understand. I am currently using Django.test.TestCase to implement my tests. I am also using the built-in self.client to send POST requests. I have been successful with model and forms tests up to this point, but now that I am testing my views, I am not able to upload my SimpleUploadedFile image. I initially created the test in a similar manner to testing my form, with all data in one data dictionary submitted to my POST request. When I received errors, I assumed it was because I needed a second dictionary for 'files'. My research has led me to become more confused on this problem. I am not sure how to include request.FILES into my POST request or if self.client is simply not able to, and I need to use a third-party library. The view that I am sending the request to is as follows: # IMPORTS from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from crm_user.forms import * from crm_user.models import Address from django.forms.models import modelformset_factory # User Profile View @login_required def profile_view(request): """ This is a User Profile view""" … -
Playwright + Django: how to wait for events
In my tests, I have to wait for an event to trigger before continuing with test assertions, but I can't figure out how to make Playwright wait for that event. It seems like Playwright can't see the event. Simple example with a django page: clicking the button fires an event boop that changes the background color of the document. Template event.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Playwright Events</title> </head> <body><button>Click me</button> <script> const btn = document.querySelector("button"); btn.addEventListener("click", (e) => document.dispatchEvent(new Event("boop"))); document.addEventListener("boop", (e) => { document.body.style.backgroundColor = "darkcyan"; }); </script> </body> </html> URL conf: urlpatterns = [ path('', TemplateView.as_view(template_name="event.html")) ] The test: def test(page, live_server): page.goto(live_server.url) page.wait_for_timeout(500) btn = page.get_by_text('Click me') with page.expect_event("boop", timeout=1000): btn.click() page.wait_for_timeout(500) When running the test in headed mode, you can see the background color changing - meaning that the event boop was fired. But the test still fails because expect_event times out: playwright._impl._api_types.TimeoutError: Timeout 1000ms exceeded while waiting for event "boop" I must be doing something wrong, but I can't figure out what. Found this similar post, but it is not about playwright-python with django. -
How to choose template in DetailView based on a field of the model shown?
I have a model with a choice field: type = models.CharField(choices=TYPE_CHOICES, max_length=1, default=UNSET, db_index=True) Depending on the type I'd like to show a different template in the class based DetailView: class AlbumDetailView(DetailView): [...] Currently I have set the template by setting: template_name = 'bilddatenbank/album_detail.html' But then it's not possible to access the value of the model field. Where can I can set the template while having access to the model? Thank you. -
Error when calling Procedure from Django: No procedure matches the given name and argument types
I want to call a stored procedure installed in our PostgreSQL database via our Django backend. According to this stack question in order to call a procedure from Django we have to type it in a file named: test.py, placed in our migrations folder, like so: from django.db import migrations SQL = """ CREATE OR REPLACE PROCEDURE get_input_file() AS $$ CREATE TABLE TEMP(RowData VARCHAR(4000)); $$ LANGUAGE SQL; """ class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [migrations.RunSQL(SQL)] NOTES: python test.py resulted in nothing. python manage.py migrate api resulted in Operations to perform: Apply all migrations: api Running migrations: No migrations to apply. Then according to this guide we have added in our backend views.py the following code: # apply stored procedure import psycopg2 import os conn = psycopg2.connect( host=os.getenv('TDB_HOST'), database=os.getenv('TDB_NAME'), user=os.getenv('TDB_USER'), password=os.getenv('TDB_PASSWORD') ) cur = conn.cursor() cur.execute("CALL get_input_file();") conn.commit() We have expected this test to successfully call the procedure. We get: procedure get_input_file() does not exist LINE 1: CALL get_input_file(); ^ HINT: No procedure matches the given name and argument types. You might need to add explicit type casts. -
Django on HTTPS with react.js
I have this website deployed and it has an ssl certificate so it uses https. Now I want to link my Django backend to it so the website works as it supposed to. The react.js frontend and the Django backend are both hosted on a single AWS Lightsail instance. Now when I make a request to my django backend (I use an IP address) for example 1.2.3.4:8000/add It complains about that I'm using HTTPS and it only accepts HTTP. Now do I have to get a certificate for the Ip address or what is the best way/place to host my Django backend. All help is greatly appreciated! -
Django serve views asynchronously
Django 3.2.8 (a relatively old version) @csrf_exempt def xhrView(request, ms, status=200): sleep(ms / 1000) response = HttpResponse( f'{status} DUMMYXHRRESPONSE IN {ms}ms' ) response['Access-Control-Allow-Origin'] = '*' response.status_code = status return response I am hosting an api server for generative data testing with django. I have views for example serving purposes like: fetch or xhr js test generate fake json based on api query generate random long text but due to the python lang nature GIL, django is not capable of serving views asynchronously, which for example, if userA is visitng xhr/10000, any other user won't be able to even access the server in that duration. in those api views I don't need to access database, is there a way to serve the view above asynchronously? p.s. I have channels installed and is using websocket somewhere else for social messaging, the proj is set to asgi. I have tried consumers.py import asyncio from channels.db import database_sync_to_async from channels.generic.http import AsyncHttpConsumer from django.http import HttpResponse class XhrConsumer(AsyncHttpConsumer): @database_sync_to_async def sleep_ms(self, ms): return asyncio.sleep(ms / 1000) async def handle(self, body): ms = int(self.scope['url_route']['kwargs'].get('ms', 0)) await self.sleep_ms(ms) response = HttpResponse(f'{self.get_status()} DUMMYXHRRESPONSE IN {ms}ms') response['Access-Control-Allow-Origin'] = '*' await self.send_response(response) def get_status(self): return getattr(self, 'status', 200) # … -
Unable to do db index from python django
I tried to indexing my db from python django model class. But while doing migrate it throw error like this. psycopg2.errors.ReadOnlySqlTransaction: cannot execute CREATE EXTENSION in a read-only transaction Please help to resolve this issue. Is it because of any access problem. My db is in azure. I am able to read and write data to the db. -
Cant override get_queryset with group by expression in django admin
I need to override get queryset method to display the total amount of orders with such status, order_unit @admin.register(models.OrderSummary) class OrderSummaryAdmin(admin.ModelAdmin): # change_list_template = 'admin/order_summary_change_list.html' date_hierarchy = 'created' show_full_result_count = False list_display = ( "order_unit", #ForeignKey "status", #ForeignKey ) list_filter = ( ('created', DateRangeFilter), ('order_unit__name', MultiSelectFilter), ('status__name', MultiSelectFilter), ) def get_queryset(self, request): qs: QuerySet = super().get_queryset(request) grouped_by_status_and_name = qs.values('status__name', 'order_unit__name')\ .annotate(total=Count('id')).order_by('order_unit__name') x = str(grouped_by_status_and_name.query) return grouped_by_status_and_name But this is falls with TypeError("Cannot call select_related() after .values() or .values_list()") Adding select_related_field helps, but i need to group by. Combination of this two(select_rel and values() is disallowed). How can I do this? PS: I am on Django 3.1 -
How to automatically increment Django IntegerField
I have a field in my model ‘’’ Step=models.IntegerField() ‘’’ I call it normally in the template with the following: ‘’’ {{user.step}} ‘’’ Now I want this field to automatically increase after every year What is the best approach here? -
django rest framework authenticate keep returning NONE
authenticate keep returning none even I'm sure from the name and the password in database and I write them right . I also check these questions, 1 and 2 but didn't help . here is my code : @api_view(['POST']) def user_login(request): print("im in login") print(request) if request.method == 'POST': name = request.data.get('name') password = request.data.get('password') print("username : ",name,"password : ",password) user = authenticate(name=name, password=password) print("user : ",user) if user is not None: # Authentication successful login(request, user) return Response({'message': 'Login successful'}) else: # Authentication failed return Response({'message': 'Invalid credentials'}) else: # Render the login form return Response({'message': 'Invalid request method'}) here is my try to authenticate: and here is user in database : I don't know what I did wrong . -
Django ORM count by date
I have Reservation model that has two fields: start_date = models.DateField() end_date = models.DateField() I need to present occupancy report based on total number of room-nights in the month, assuming each reservation takes one room during the day. So either I need to: annotate each reservation with number of days (but only in the queried month) or for each date lookup number of reservations: filter(start_date__lte=date, end_date__gte=date) I've done solution 2 in python: month, year = 9, 2023 cal = calendar.Calendar().itemonhtdates(year, month) cal = [date for date in cal if date.month = month] res = Reservation.objects.filter(Q(start_date__range=cal) | Q(end_date__range=cal)) occupied_rooms = 0 for d in date: occupied_room += res.filter(start_date__lte=d, end_date__gt=d).count() But python solution is too slow. Is it possible to achieve same result on database level? -
Is there a way to return 3 files together with some data calculations from one Django request?
I have a Django request doing some ML calculations. The request takes 3 files as input and generates 3 files as an output together with some temperature data calculations that I need. If I try using **rest_framework.response **then I get: TypeError: keys must be str, int, float, bool or None, not tuple from rest_framework.response import Response return Response(thermal_response["data"], status=thermal_response["statusCode"]) If I try using JSONResponse I get: TypeError: Object of type ndarray is not JSON serializable from django.http import JsonResponse JsonResponse(thermal_response["data"], safe=False) -
Configuring Django App with Docker, Traefik, Custom TSL - How to?
I am trying to setup a django-app in a docker container using traefik as reverse proxy with custom tsl certificates in a docker-compose.yml. But I do not amanage to get this going. Using the below configuration, I manage to serve the app as http, but https does not work. docker-compose.yml: version: '3.9' services: traefik: image: "traefik:v2.10" container_name: traefik hostname: traefik command: #- "--log.level=DEBUG" # - --api.insecure=true - --providers.docker=true - --providers.docker.exposedbydefault=false - --entrypoints.web.address=:80 - --entrypoints.websecure.address=:443 - --providers.file.directory=/configuration/ - --providers.file.watch=true ports: - "80:80" - "443:443" # - "8080:8080" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - "./configuration/:/configuration/" networks: - traefik-public dbdevdanjgo: image: mariadb restart: always environment: MYSQL_ROOT_PASSWORD: danjgocou MYSQL_DATABASE: mydbdevdanjgo MYSQL_USER: userdanjgo MYSQL_PASSWORD: ${DB_PASSWORD} volumes: - /data/myapp/mariadb/ecrf/data:/var/lib/mysql - /data/myapp/mariadb/ecrf/logs:/var/log/mysql myapp: image: myrepo/myapp2:v1.0 command: bash -c 'sleep 30; gunicorn --bind 0.0.0.0:8000 myapp.wsgi' expose: - 8000 environment: - DEBUG=${DEBUG} - DJANGO_ALLOWED_HOSTS=${APP_DOMAIN} - CSRF_TRUSTED_ORIGINS=https://${APP_DOMAIN} - DB_PASSWORD=${DB_PASSWORD} - SECRET_KEY=${SECRET_KEY} labels: - traefik.enable=true - traefik.docker.network=traefik-public - traefik.constraint-label=traefik-public - traefik.http.routers.myapp-http.rule=Host(`${APP_DOMAIN}`) - traefik.http.routers.myapp-http.entrypoints=http - traefik.http.routers.myapp-http.middlewares=https-redirect - traefik.http.routers.myapp-https.rule=Host(`${APP_DOMAIN}`) - traefik.http.routers.myapp-https.entrypoints=https - traefik.http.routers.myapp-https.tls=true networks: - traefik-public restart: unless-stopped networks: traefik-public: external: false -
how to link urls path with views in django
`I am developing an ecommerce website on Django I need help on how to link URLs with the views. Here is the URL: from django.urls import path from . import views urlpatterns = [ path('search/', views.search, name='search'), path('<slug:slug>/', views.category_detail, name='category_detail'), path('<slug:category_slug>/<slug:slug>/', views.product_detail, name='product detail'), ] This is the view: from django.db.models import Q from django.shortcuts import render, get_object_or_404 from .models import Category, Product def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return render(request, 'store/category_detail.html', { 'category': category, 'products': products, }) enter image description here Attached is the error I get. I am expecting to see the web page.` -
Docker project is working fine on local environment but not working on production on ec2 instance
I am beginner to docker, I am able to run project in local environment but same thing is not working on ec2 instance I have already changed public id's to reflect changes, here are the configurations I have done so far File Structure Docker File env file Nginx Configuration File Nginx file in Docker Setting.py docker compose.yml entry point file Build Successful on server I have tried the public ip added in configuration but I am unable to access and also there is no logs in the console I tried different configurations but nothing works although on ec2 instance I have allowed all inbound ports -
Why is my cache not invalidated when using cachalot and Django?
My project uses Django version 4.1.9 and cachalot 2.5.3 (latest version). I just added the CACHES (BACKEND: "django.core.cache.backends.redis.RedisCache") option in Django and added the UpdateCacheMiddleware and FetchFromCacheMiddleware middlewares plus added "cachalot" to my installed_apps. Now when I patch/ put anything I am getting a correct and updated response (200 with the changes) but when I try to GET the resource it still shows the old response (200 without the changes). Why doesn't Django cachalot invalidate the cache on patching the objects? -
Validating if objects have been selected in a ManyToManyField in Django?
I am trying to create a def clean(self): function, to validate if my objects have been selected. This is my Code so far: class Situation(models.Model): considered_malfunctions = models.ManyToManyField( Functions, related_name='Situations', limit_choices_to={'is_important': True}, reason = models.TextField(max_length=255, null=True, blank=True) so my clean function should check if an "is_important"-object from Functions is not selected. Then the TextField in reason must be filled. If every object got selected, there is no need for a text in reason. -
graph not working properly in django, getting syntax error
I am new to Django, I want that user should be able to see the count of total user registered in that month, and will count chnages on every month view.py monthly_data = ( Clinic.objects .filter(updated__range=(start_of_month, end_of_month)) .annotate(month=TruncMonth('updated')) .values('month') .annotate(count=Count('register_clinic_user_id')) .order_by('month') ) labels = [data['month'].strftime('%B %Y') for data in monthly_data] data = [{'month': data['month'].strftime('%B %Y'), 'count': data['count']} for data in monthly_data] graph_data = json.dumps(data) print("------------------------------------", graph_data) print("----------------------------------------", labels) js new Chart(ctx2, { type: "line", data: { labels: ["Jan","Feb","Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], datasets: [ { label: {% for label in labels %} {{label}}, {%endfor%}, tension: 0.4, borderWidth: 0, pointRadius: 0, borderColor: "#16b385", borderWidth: 3, backgroundColor: gradientStroke1, fill: true, data: {% for graph_datas in graph_data %} {{graph_datas}}, {%endfor%}, maxBarThickness: 6, }, ], }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false, } }, interaction: { intersect: false, mode: 'index', }, scales: { y: { grid: { drawBorder: false, display: true, drawOnChartArea: true, drawTicks: false, borderDash: [5, 5] }, ticks: { display: true, padding: 10, color: '#b2b9bf', font: { size: 11, family: "Open Sans", style: 'normal', lineHeight: 2 }, } }, x: { grid: { drawBorder: false, display: false, drawOnChartArea: false, drawTicks: false, borderDash: … -
Django normalize() is showing 1E+2
I'm trying to create a function in my model to display product info, and in my model I have the following: class Product(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) @property def product_label(self): return f'The product price is {self.price.normalize()}' Using normalize() is working fine if the price is something like 10.50 The output is as the following, which is what I exactly want: The product price is 10.05 BUT when I have a price like 10.00, the output displayed shows 1E+1 instead of 10 The product price is 1E+1 Is there any idea how can I fix this issue? -
Aliyun esc + uwsgi + nginx + django: Website down with no logs - what steps can I take to debug?
The configured uwsgi and nginx are as followsenter image description here and enter image description here server open port enter image description here The website is currently inaccessible, including static resources, and the previous log files are no longer output what should I do? Both uwsgi and nginx are running normally enter image description here -
ClientError at /api/document/ An error occurred (403) when calling the HeadObject operation: Forbidden
I'm getting this error while I'm trying to upload a fil into s3, The following is my bucket policy { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowGetAndHead", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::monover-052023-s3bucket/*" }, { "Sid": "S3PolicyStmt-DO-NOT-MODIFY-1684257818955", "Effect": "Allow", "Principal": { "Service": "logging.s3.amazonaws.com" }, "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::monover-052023-s3bucket/*" } ] } does this has any error that cause this error please help me to fix it I tried a couple of ways to fix but not working also does this can be occurred due to any code issue if so where might it get happens please share your thoughts also Here is my setting.py where the connection is made, I double-checked the AWS credentials and also no issues find DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_ACCESS_KEY_ID = "AKIAZO7XJSQ54CWZNR6K" AWS_SECRET_ACCESS_KEY = "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" AWS_STORAGE_BUCKET_NAME = "django-monover-textract" AWS_QUERYSTRING_AUTH = False AWS_S3_FILE_OVERWRITE = False -
Django + React js not able to render homepage correctly
I am trying to create a web application with Django and Reactjs. My goal is to create a homepage with username and password prompt and a submit button. When I run the program the webpage is rendering blank page and the expected behavior is to show username and password form on the webpage written in typescript.It shows a blank page with following response prasku@Praskus-Air nekikx_main % python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 25, 2023 - 08:22:11 Django version 4.2.1, using settings 'nekikx_main.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [25/May/2023 08:22:14] "GET / HTTP/1.1" 200 634 [25/May/2023 08:22:15] "GET /static/js/main.js HTTP/1.1" 200 0 [25/May/2023 08:22:15] "GET /static/js/index.js HTTP/1.1" 200 295 [25/May/2023 08:22:15] "GET /static/js/test.js HTTP/1.1" 200 1175 urls.py from django.contrib import admin from django.urls import path from django.conf.urls.static import static from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] urlpatterns += static('/static/', document_root='frontend/build/static') views.py from django.shortcuts import render def home(request): return render(request, 'home.html') home.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Include React and other dependencies --> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> </head> <body> <!-- Placeholder for React …