Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project, Assertion Error: 200 != 302
I am trying to get my tests to run successfully and I am not sure what I am missing with this. here is my tests.py from django.test import TestCase, Client, override_settings from .forms import CommentForm, PostForm, PostEditForm from django.urls import reverse from .models import Post from django.http import HttpResponseRedirect from django.views.generic.edit import CreateView from django.contrib.auth.models import User from django.urls import reverse_lazy class PostTests(TestCase): def setUp(self): self.user = User.objects.create_user(username='testuser', password='testpassword') self.post = Post.objects.create( title='Test Post', content='This is a test post content.', author=self.user, ) def tearDown(self): if hasattr(self, 'user'): self.user.delete() if hasattr(self, 'post'): self.post.delete() def test_post_detail_view(self): response = self.client.get(reverse('news:post_detail', kwargs={'slug': self.post.slug})) self.assertEqual(response.status_code, 302) def test_post_add_view(self): self.client.force_login(self.user) response = self.client.post(reverse('news:post_add'), data={'title': 'New Test Post', 'content': 'Test content'}) self.assertEqual(response.status_code, 302) self.assertRedirects(response, reverse('news:post_detail', kwargs={'slug': 'new-test-post'})) new_post = Post.objects.get(title='New Test Post') self.assertEqual(new_post.author, self.user) self.assertRedirects(response, reverse('news:post_detail', kwargs={'slug': new_post.slug})) views.py: from django.shortcuts import render, get_object_or_404, reverse, redirect from django.views import generic, View from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import ListView from django.views.generic.edit import CreateView, DeleteView from django.views.generic.detail import DetailView from django.utils.text import slugify from django.urls import reverse_lazy from django.http import HttpResponseRedirect from .models import Post, Category, Article from .forms import CommentForm, PostForm, … -
how to use same url and class for put, get, post, delete functions in drf class base api
in my views file I want to have this logic: class Articles(APIView): def get(self, reqeust, id): #logic def put(self, request, id): #logic def post(self, requst, id): #logic def delete(self, request, id): #logic and I want handle urls like this : /articles/int:pk # articles shows with id=pk /articles/add # add article to db and so on... but I have problem that I dont want to use different class and at the same time i want that if I call /articles/add post method call , what is the best way to implement this? sry I'm very new to python and drf, I will be thanks to help me to do this in best way, is the way I'm thinking to handle this totally wrong? I just I don't want to have different class in APIView approach using drf for every single post, get, ... ones. -
How can I insert a QR code reader in my django application to verify if a code exists on the database?
I have a django app of musical show tickets that a QR code is generated and saved on the database after every sale of a ticket. Now I'm trying to create a page that will read these QR codes to verify if it exists on the database. HTML: <h1>QR code reader</h1> <video name="qr-video" id="qr-video" width="100%" height="100%" autoplay></video> <script> const video = document.getElementById('qr-video'); navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }) .then((stream) => { video.srcObject = stream; return new Promise((resolve) => { video.onloadedmetadata = () => { resolve(); }; }); }) .then(() => { video.play(); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; setInterval(() => { context.drawImage(video, 0, 0, canvas.width, canvas.height); const imageData = context.getImageData(0, 0, canvas.width, canvas.height); const code = jsQR(imageData.data, imageData.width, imageData.height); if (code) { alert('QR code read: ' + code.data); sendQRcode(code.data); } }, 1000); }) .catch((error) => { console.error('Error trying to access camera: ', error); }); function sendQRcode(code) { alert('QR code sent') const url = 'https://ac7-1bd37c9a12e8.herokuapp.com/show/scanner/'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, body: JSON.stringify({ code: code}), }) .then((response) => { response.text().then((text) => { alert('Response from server:', text); }); if (!response.ok) { throw new Error('Network response was not ok'); … -
Django frontend convenient handle different responses
I am unsure how to deal with different return options in Django. Let me describe a fictive scenario: I have an endpoint /books/5/ that returns an html showing infos about the book and the chapters it contains. Those are reachable at /books/5/chapters/ and /books/5/chapters/3/ for example. I can make a POST to /book/5/chapters/ via a form with title etc. to create a new chapter. This can either succeed and a new chapter is created or it can fail, because of whatever reason. To make my frontend a bit convenient I included the form to create chapters at the endpoint /book/5/. So I can see the books details and chapters and enter details for new chapter in this view in the form and click create. My desired experience would be that I get a refresh of the /book/5/ to see the new state. If the post failed I would like to see a notification with the error message. Is there a standard way how to do this? I have played around with JsonResponse and returning the next URL to go to and calling the endpoint with a JavaScript function that sets the current window to it. Vut I don't know how … -
post_save seams has bug
my simplified problem is below: i have a model like this: class Alert(models.Model): ALERT_CHOICES = [("email","email"),("sms","sms"),("notif","notif")] name = models.CharField(max_length = 50) owner = models.ForeignKey(User , on_delete=models.CASCADE) coins = models.ManyToManyField(Coin,blank=True) when an object of Alert like alert changes. i want to print number of coins that connected to alert after change in this method: @receiver(post_save, sender=Alert) def handle_alert_save(sender, instance, **kwargs): coins = instance.coins.all() print(len(coins)) Unfortunately! it prints number of coin before change alert. i want after change the object. in other words post_save signal is exactly equal to pre_save. for example when i have 2 connected coin to aler and i change it to 5. it prints 2! i try all other signals like pre_save and pre_delete and pre_migrate and post_migrate. -
Django Aws ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden
I am trying to upload my static files to Amazon S3 from my django project using boto3 and django-storages modules. Here is the AWS S3 configurations in my settings.py file AWS_ACCESS_KEY_ID = "<public-key>" AWS_SECRET_ACCESS_KEY_ID = "<private-key>" AWS_STORAGE_BUCKET_NAME = "<bucket-name>" STORAGES = { # Media files (images) management "default": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, # CSS and JS file management "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", }, } AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False I have given AmazonS3FullAccess permission policy to the IAM user. and here is my bucket policy: { "Version": "2012-10-17", "Id": "Policy1706347165594", "Statement": [ { "Sid": "Stmt1706347164281", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::<bucket-name>/*" } ] } previously I only gave PutObject action it didn't work. I was gettting the same error given below. Im using the python manage.py collectstatic command to upload to S3 You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/home/gajeet/Documents/Django/Django_ultimate/dev2/manage.py", line 22, in <module> main() File "/home/gajeet/Documents/Django/Django_ultimate/dev2/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/gajeet/Documents/Django/Django_ultimate/dev2/.venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File … -
Unable to Push to Bitbucket Repository: Git Push Error
hi everyone I tried to push some project into bit bucket but it just gives me the message of permission denied(public key) fatal: could not read from remote repository. and idk why i entered every thing just like the book. thank you so much for answering. I tired re writing the project or trying with my other codes but the problem is still there. -
Celery does not see objects in SQLite (in Docker)
I have project on Django, DRF, SQLite, RabbitMQ and Celery. When I run the project locally (separately rabbitmq, celery and django), everything works correctly. But when I run it in Docker, the task in celery does not find an object in the database. Attempts to find the created task from the celery container shell are also unsuccessful (I only see old objects). If I enable CELERY_TASK_ALWAYS_EAGER=True setting, then everything works fine in Docker. settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } docker-compose.yaml version: "3.7" services: rabbitmq: restart: always container_name: "rabbitmq" image: rabbitmq:3-management-alpine ports: - 5672:5672 - 15672:15672 app: restart: always container_name: "fbrq_api" build: . volumes: - .:/code command: python3 manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" celery: restart: always container_name: "celery" build: context: . command: celery -A fbrq_api worker -l info env_file: - ./.env depends_on: - app - rabbitmq environment: - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/ celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fbrq_api.settings") app = Celery("fbrq_api", broker="amqp://guest:guest@rabbitmq:5672/") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f"Request: {self.request!r}") I understand that SQLite is not the best choice, but I think it's not about the database itself, but about the connection between Celery and the database. -
Get Value of Iterable Element
I have a list as shown below. Now I want to get the values of each radio button when clicking on it. However, I get always the first value since the IDs (list-name) will be the same when rendered out the list. Is there a simple way to do so? Maybe with onclick=function(this) <form id="form-1"> {% for u in user %} <li> <div> <input id="list-name" type="radio" value="{{ u.name }}" name="list-radio"> <label for="list-name">{{ u }}, {{ u.name }}</label> </div> </li> {% endfor %} </form> <script> $(document).on('change', '#form-1', function (e){ console.log($('#list-name').val()) } </script> -
Merge video and audio using ffmpeg and download immediately in django
I have video and audio file which is to be merge and download automatically. I have written some code but it will start download after merged. I want when user hit the url, then it will start merging and downloading immediately so that user don't have to wait for it. video_url = "./video.mp4" audio_url = "./audio.mp4" output_filepath = './merged.mp4' try: process = subprocess.Popen([ "ffmpeg", "-i", video_url, "-i", audio_url, "-c:v", "copy", "-c:a", "copy", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1" ], stdout=subprocess.PIPE) def generate_stream(): while True: data = process.stdout.read(1024) if not data: break yield data response = StreamingHttpResponse(generate_stream(), content_type="video/mp4") response['Content-Disposition'] = 'attachment; filename="stream.mp4"' return response except subprocess.CalledProcessError as e: return HttpResponse("Error: {}".format(e), status=500) But it will merge and then start downloading. I want to be at same time so that user don't have to wait until the merging process. I am using django and i am learning django -
How to make a div overflow beyond its parent's boundaries when hovered over?
for starters, here is code that works: {%for movie in topRated%} <div class="container2"> {%with base_url="https://image.tmdb.org/t/p/original/"%} <img class="img-1" src={{base_url}}{{movie.poster_path}}> {%endwith%} <div class="info2"> <div class="year-rating"> <span class="yrtext">{{movie.release_date}}</span> <span class="yrtext">{{movie.vote_average}}</span> </div> <div class="movietitle2"> <a href="{% url 'movieDetails' movie.id %}" class="movietitlespan">{{movie.title}}</a> </div> </div> </div> {%endfor%} </div> the css code for the above is the following: .moviePage .indexdiv2 .flow-into2{ margin-top: 30px; display: flex; align-items: start; flex-direction: column; padding-left: 25px; } .moviePage .indexdiv2 .container2{ width: 400px; height: 150px; display: flex; flex-direction: row; border-radius: 7px; /*overflow-x: hidden; overflow-y: visible;*/ position: relative; margin-top: 10px; margin-bottom: 25px; scale: 1; transition: transform 0.3s ease; /* Apply transition to .container2 */ z-index: 10; } .moviePage .indexdiv2 .container2:hover { transform: scale(1.5); /* Scale the entire container on hover */ z-index: 100; } .moviePage .indexdiv2 .number-icon{ margin-right: -20px; height: 50px; width: 50px; z-index: 5; position: relative; } .moviePage .indexdiv2 .img-1{ height: 149px; position: relative; z-index: 2; scale: 1; transition: scale 0.3s ease; } As you can see from the above, the code works where i hover over the container, it scales up and above its parent div and sister elements, which is shown in the following image: and this. the problem lies in the following code, which aims to have a similar behaviour, … -
I am using a Hostinger VPS cloudhost to host a django Backend , everything working fine while hosting IP address and port but not in domain?
Hosting Problem Its showing like this , But in IP address its is working fine all the images are fetching from backend... See this also coming like this but its working in IP address with port its working fine ,while in domain its not working or posting the form if i check the hosting method its working fine but its not working good in my domain ,do i have to change something in server conf file -
When I write a python django for loop, it does not return the data I created in the model [closed]
I can see everything I defined in the model in the admin panel, but when I write a for loop in html, the data I defined does not appear. this is my model: enter image description here this is my view: enter image description here this is my url: enter image description here this is my for loop code: enter image description here this is my admin panel: enter image description here after writing for loop code: enter image description here before writing for loop code: enter image description here I would be very grateful if you can help me where I made a mistake. Thank you in advance. -
Connecting multiple Reddit accounts associated with one user in Python-Django
I want to create a website like postpone using Django and PRAW and I want to create a service that user can connect his/her multiple Reddit accounts and he/she can create schedule posts on reddit so far, I did this. I created custom user model: # customers/models.py import uuid from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class CustomerManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have email') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user(email=self.normalize_email(email), password=password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Customer(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) data_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = CustomerManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True And I added my reddit account informations such as client_id, client_secret and user_agent: # customers/reddit_conf.py import praw from django.http import HttpResponse from django.shortcuts import redirect from oauthlib.oauth2 import WebApplicationClient from django.contrib.auth import get_user_model import requests import secrets User = get_user_model() # Reddit App Configuration client_id = "****************", client_secret = "**************", redirect_uri='http://127.0.0.1:8000', user_agent="****** by u/******", … -
In Django how can i execute multiple if/else conditions in a function and print their result to a div?
I would like to execute some multiple conditions (if/else) in the def function_check function and print their multiple result in a grey div, for example like this: Initially i had all the code in the same function, now i have divided it into two functions and mentioned the difficulties, so i want to continue using 2 separate functions: def function_input_user and def function_check. Precisely, the app checks if there are words in a textarea (user_input.html). If there are, then I would like to print a message in the grey div. I'm new to Django, my difficulties are with context and return JsonResponse(context, status=200), because i can't return all multiple condition results and print them in the colored div. I get error: raise TypeError( TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/a.css' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> </head> <body> <div class="test"> <div>Input User</div> <div class="editor"> <pre class="editor-lines"></pre> <div class="editor-area"> <pre class="editor-highlight"><code class="language-html"></code></pre> <textarea class="editor-textarea" id="userinput" data-lang="html" spellcheck="false" autocorrect="off" autocapitalize="off"> &lt;!DOCTYPE html> &lt;html> &lt;head> &lt;title>Page Title&lt;/title> &lt;/head> &lt;body> &lt;div … -
Django Restframework designs are not working After Hosting?
i hosted a application but the restframework design like the redcolor form alignments are not working , without design only texts are there , how to get the restframework design need to show the restframework design and also the ststicfiles will be working properly -
Django: creating form with unknown amount of select input
i have form in my template that works well but i want to "convert" this form to django form. In my class register i have form with unknown amount of selects because in one class i can have 12 students in other 18. Here is my code: html <form method="post"> {% csrf_token %} <table class="table"> <thead> <tr> <th>ID</th> <th>first name</th> <th>last name</th> <th>January</th> <th>February</th> <th>March</th> <th>April</th> </tr> </thead> {% for student in students %} <tbody> <!-- Grades --> <tr> <td>{{ student.id }}</td> <td>{{ student.student.first_name }}</td> <td>{{ student.student.last_name }}</td> <td> <!-- Grades for January - for testing purpose --> {% for grade in grades %} {% if grade.student.id == student.id and subject == grade.subject %} {{ grade.display_value }} {% endif %} {% endfor %} </td> <td></td> <td></td> <td></td> <td></td> <td> <div class="form-group grade-select"> <select class="form-select" id="id_grade_{{student.id}}" name="grade_{{student.id}}"> <option value="0" selected disabled hidden>Grade</option> <option value="1">1</option> <option value="1+">1+</option> <option value="2">2-</option> <option value="2">2</option> <option value="2+">2+</option> <option value="3-">3-</option> <option value="3">3</option> <option value="3+">3+</option> <option value="4-">4-</option> <option value="4">4</option> <option value="4+">4+</option> <option value="5-">5-</option> <option value="5">5</option> <option value="5+">5+</option> <option value="6-">6-</option> <option value="6">6</option> </select> </div> </td> </tr> </tbody> {% endfor %} </table> <div class="form-group grade-select"> <select class="form-select" id="id_assigment" name="assigment"> <option value="0" selected disabled hidden>assigment</option> {% for assigment in assigments %} … -
In Django, i can't print a simple string message that contains the > and < characters. The characters are ignored and not printed
In Django i'm trying to print a simple message as a return of a function. if '<html>' in file2_processed: context["message"] = "CORRECT: <html> found" else: context["message"] = "ERROR: <html> not found" PROBLEM: The problem is that <html> is not printed, so the printed output is: CORRECT: found or ERROR: not found ATTEMPTS: I tried using repr(text) or text.encode().decode('raw_unicode_escape'), but it doesn't work. How can I solve it and print CORRECT: <html> found or ERROR: <html> not found ? -
Docker containers not able to communicate to each other
I'm trying to prepare a docker-compose.yml file to serve a django app. I have two services: the web server (using gunicorn) the database (Postgres) this is my docker-compose.yml file version: '3' services: db: image: postgres:latest container_name: db ports: - "5433:5433" volumes: - ./postgres_data:/var/lib/postgresql/data environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_DB=postgresdb - POSTGRES_USER=admin - POSTGRES_PASSWORD=admin web: image: django-app:latest build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - .:/app depends_on: - db volumes: postgres_data: My Dockerfile file: # Use the official Python image as a base image FROM python:3.11-slim-buster # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV BUD_DATABASE_HOST postgresql.test ENV BUD_DATABASE_PORT 5433 ENV BUD_DATABASE_NAME postgresdb ENV BUD_DATABASE_USER admin ENV BUD_DATABASE_PASSWORD admin ENV DJANGO_SETTINGS_MODULE app.settings.dev # Instalación de paquetes adicionales RUN apt-get update && apt-get install -y \ postgresql-client build-essential libpq-dev \ && rm -rf /var/lib/apt/lists/* # Set the working directory WORKDIR /app # Install dependencies COPY requirements.txt . RUN pip install --upgrade pip && pip install -r requirements.txt # Copy the Django project files COPY . . # Run migrations and collect static files RUN python manage.py migrate RUN python manage.py collectstatic --noinput # Start the Django development server CMD ["gunicorn", "app.wsgi:application", "--bind", "0.0.0.0:8000"] And app/settings/dev.py file: from app.settings.base import … -
Access blocked: authorisation error Gcloud
When using this docker command docker-compose -f docker-compose-deploy.yml run --rm gcloud sh -c "gcloud auth login", then it gives this error on clicking the URL: Cloud Authorization error which reads "The version of the app you're using doesn't include the latest security features to keep you protected. Please make sure to download from a trusted source and update to the latest, most secure version." "Error 400: invalid_request" Here's the screenshotError Screenshot Note: While using normal "gcloud auth login", without docker it logins successfuly -
Google OAUTH2: error_description: 'Invalid client_id parameter value with 400 error
this is my login.jsx import axios from "axios"; import {Navigate} from "react-router-dom"; import {useState} from "react"; import GoogleLogin from "react-google-login"; import {gapi} from "gapi-script"; import {useEffect} from "react"; import 'bootstrap/dist/css/bootstrap.css'; export const Login = () => { const clientId = "252855945185-0fm1oqq2945rkv2sak6satjgvopiiv1o.apps.googleusercontent.com"; const onSuccess = async (res) => { console.log('succzddgsfgess:', res.accessToken); const user = { "grant_type":"convert_token", "client_id":"", // <==== replace with google client_id from google console "client_secret":"", // <==== replace with google client_secret from google console "backend":"google", "token": res.accessToken }; console.log("hi") console.log(user) const {data} = await axios.post('http://localhost:8000/api-auth/convert-token/', user ,{headers: { 'Content-Type': 'application/json' }}, {withCredentials: true}); <=== where error caused console.log('API Response:', data); console.log(data, data['access_token']) axios.defaults.headers.common['Authorization'] = `Bearer ${data['access_token']}`; localStorage.clear(); localStorage.setItem('access_token', data.access_token); localStorage.setItem('refresh_token', data.refresh_token); try{ window.location.href = '/' }catch(error){ console.error("error", error); } } const onFailure = (err) => { console.log('failed:', err); }; return( <div className="Auth-form-container"> <GoogleLogin clientId={clientId} buttonText="Sign in with Google" onSuccess={onSuccess} onFailure={onFailure} cookiePolicy={'single_host_origin'} /> </div> ) } this is my settings.py """ Django settings for config project. Generated by 'django-admin startproject' using Django 4.2.7. 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 = … -
Try to Display Number of Choice Selected at Any Time on Django Form MultipleChoiceField
I am building an application for a real estate project. As part of this, I have "listing" items in my database that I filter and display on my SearchTool.html page. One of the search functions includes a button that says "Select Property Type" on it. When you click the button, a small popup displays all of the multiple-choice field options from my Django form. I want the button to show how many choices are selected so that if the popup is closed you don't have to reopen it to know how many are active. Currently, it seems to mostly work. The popup works great. But, the counter has some problems. When I select exactly on the checkbox then the counter works fine but when I select the text to toggle the choice the counter doesn't catch it. When I click on the text like this, the backend still registers it because it sorts my listings correctly. So, there is an issue with the html/js not registering when I select the text vs the box itself. I am new to Django so please let me know if this question has been answered or if I am missing something obvious. Here is … -
Problem understanding serializer.data structure
I need some help from someone with better knowledge than myself, to understand this. I have a queryset of data and some context data that I send into a rather complex ModelSerializer. The Modelserializer adds (using the context data) fields to the data that doesn't come from the model itself. When I then look at serializer.data it looks like [OrderedDict([('field1', value1), ('field2', value2),....]),OrderedDict([('field1', value1), ('field2', value2),....])] when I drill down into next level for item in serializer.data: print(item) Output: OrderedDict([('field1', value1), ('field2', value2),....]) how can I access value1, value2 ? if I iterate in next level it only generates the key values,'field1','field2' etc for i in item: print(i) Output: 'field1' I understand there might be much better functions. But I'm doing it this very simple way to try to understand the structure of the data (without success aparantly). I hope someone understands my question and is able to explain to me. I've been playing around with deserialisation but I suspect the structure of the modelserializer doesn't allow it to be used. Is it correct that deserialisation only work on datasets that are 100% generated from the model in the Modelserializer in question? -
Seperated Django frontend and Django backend?
So I am creating my first django project for work and I think I am getting familar with it. I designed my views and URLs strongly oriented to REST principles. But since I render html and use forms to manipulate data, it is actually not REST in terms of pushing or pulling data. I have actually no desire to create a separated frontend in a different framework running at a different adress. But I wondered if it would be a reasonable idea to create an app frontend in my project and make all the other apps serve and receive json to make them restfull. Then I could use the frontend app to render the templates and query the data from the other endpoints. But maybe it's a stupid idea for reasons I don't see or I am unsure about. -
There is no method named delay() in celery shared_task decorator, how to fix it?
# orders/tasks.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): order = Order.objects.get(id=order_id) subject = f'Order nr.{order.id}' message = f'Dear {order.first_name},\n\n You have successfully placed an order. Your order ID is {order.id}.' mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email]) return mail_sent # orders/views.py from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart from .tasks import order_created def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity'] ) cart.clear() order_created.delay(order.id) return render(request, 'orders/order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'form': form}) i imported celery in my project , and want to create an asynchronous task, after reading celery docs i think i do everything right , and still delay method does not exist Django==5.0.1 celery==5.3.6