Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to best model a tree of generic content types in Django?
I have a Django API for managing a bunch of content related to D&D campaigns: characters, locations, factions, quests, etc. Until now the frontend has always displayed these types of content in their own tabs, so a list of characters, another list of locations, and within a tab content can be nested: locations can have sub-locations, but they are all in their own "silo". class Location(models.Model): name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True) text = models.TextField(blank=True) icon = models.CharField(max_length=255, default="map-location-dot") parent = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, null=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) I am thinking about turning the frontend into one nested tree of all content types: so a location could have nested factions, which could have nested characters, and so on, totally free-form. I'm not really sure how to best model this in the database. One idea I have is to create a brand new model that contains the tree, with generic relations to content items via the contenttypes framework from Django. class Tree(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") parent_content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) parent_object_id = models.PositiveIntegerField(null=True) parent_content_object = GenericForeignKey("content_type", "object_id") order = models.PositiveIntegerField() campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) That would work (although I … -
Cannot add <Image> instance is on database "default", value is on database "None"
I'm developing and app in Django, and I'm getting this error when my form y submitted, the problem is given when it try to add images on the relationship ManyToMany. Internal Server Error: /publish_offer/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\management\views.py", line 49, in publish_offer oferta.imagenes.add(*imgs) File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1137, in add self._add_items( File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1397, in _add_items target_ids = self._get_target_ids(target_field_name, objs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1313, in _get_target_ids raise ValueError( ValueError: Cannot add "<ImagenesOferta: ImagenesOferta object (None)>": instance is on database "default", value is on database "None" [29/Jun/2023 16:10:20] "POST /publish_offer/ HTTP/1.1" 500 87580 This is my models: class ImagenesOferta(models.Model): imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/') class Meta: verbose_name = 'Imagen de Oferta' verbose_name_plural = 'Imagenes de Ofertas' ordering = ['-id'] class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=4, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = … -
How to access WSGIRequest multiple times?
I have an APIView that calls another APIView for check purpose, But after hours of searching I know now that it's not easy to access HttpRequest after turn into stream object and will cause the below error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream some are suggest to use request.data not request.body but I can't do it in such case: B.views.py from rest_framework import views from rest_framework.response import Response from A.views import A class B(views.APIView): def post(self, request, *args, **kwargs): http_response = A.as_view()(request._request) # So far so good, but if I want to access request.data after calling A.as_view() will raise # the exception. return Response(http_response.data) How to deal with this issue? source: issue2774 -
create constance django from model list
I need to implement functionality when only one user of users Model can has 'editor-role' I will use this constant in my drf api. So I need to create some django constant with one user id, and dropdown menu of all users in my django admin panel. How can I do it? I choose django-constant, but faced with the problem that list of model data couldn't init in settings py: CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_ADDITIONAL_FIELDS = { 'users_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ( (None, "-----"), User.objects.all().split(",")) ) }], } CONSTANCE_CONFIG = { 'DEFAULT_USER': ('', 'default user', 'users_select'), } Any another ideas how to implement this functionality? -
Django hide media files link for certain people
I programmed a function where you can download a file from the media folder with the media files depending on the link. The problem is that if you change the path in the link you have access to all the media files and not just the ones you are supposed to download. Can I somehow ban the other links (with a permission or something) or is there a clever way to solve the whole thing? -
Is `pytz` deprecated now or in the future in Python?
pytz is used in the Django version: <=3.2 doc Selecting the current time zone as shown below: import pytz # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) But, zoneinfo is used instead of pytz in the Django version: 4.0<= doc Selecting the current time zone as shown below: import zoneinfo # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(zoneinfo.ZoneInfo(tzname)) else: timezone.deactivate() return self.get_response(request) My questions: Is pytz deprecated now or in the future in Python? Why isn't pytz used in the Django version: 4.0<= doc Selecting the current time zone? -
Django form saves only the last row, times the number of records in the form
I have a form which saves data. The problem is, only the last row of the form gets saved, multiplied by the number of records that appear in the form. I have a feeling that only the last data row is being passed, and it is being looped through. However, for the life of me, I just cannot figure this out. Thanks in advance for help. Here is the relevant code: Model: class MonthlySheet(models.Model): employeename = models.ForeignKey(Employees, on_delete=models.CASCADE, related_name='monthlysheets') uan = models.CharField(max_length=12) ip = models.CharField(max_length=15) epfowages = models.IntegerField() esicwages = models.IntegerField() twelve_percent = models.IntegerField() eight_three_three_percent = models.IntegerField() difference = models.IntegerField() working_days = models.IntegerField() ncp = models.IntegerField() zero_point_seven_five_percent = models.IntegerField() Form: class MonthlySheetForm(forms.Form): print("Starting monthlysheetform class validation") employeename_id = forms.IntegerField(required=True) establishmentid = forms.IntegerField(required=True) uan=forms.CharField(required=True) ip=forms.CharField(required=True) epfowages = forms.IntegerField(required=True) esicwages = forms.IntegerField(required=True) twelve_percent = forms.IntegerField(required=True) eight_three_three_percent = forms.IntegerField(required=True) difference = forms.IntegerField(required=True) working_days = forms.IntegerField(required=True) ncp = forms.IntegerField(required=True) zero_point_seven_five_percent = forms.IntegerField(required=True) def clean(self): print("Cleanse starting in MonthlySheetForm") cleaned_data = super().clean() epfowages = cleaned_data.get('epfowages') esicwages = cleaned_data.get('esicwages') establishmentid = cleaned_data.get('establishmentid') employeename_id = cleaned_data.get('employeename_id') return cleaned_data View: def add_monthlysheet(request): assert isinstance(request, HttpRequest) establishments = Establishment.objects.all() employees = [] establishmentname = request.session.get('establishmentname', '') establishment_id = '' # Set initial value for establishment_id monthlysheet = MonthlySheet.objects.all() if … -
What is the best way to save comma separated keywords posted from client side into database table using Django?
I have a text area input on a simple HTML page, where I am posting comma-separated keywords to save into my database table. For example, Keywords input is like: keyword1,keyword2,keyword3, ... I am using Django 3.2 and Tastypie as a API framework. Here is my Django model: class Keywords(models.Model): keyword = models.CharField(max_length=200, unique=True) class Meta: db_table = 'keywords' And Tastypie resource: class KeywordResource(ModelResource): class Meta(CommonMeta): queryset = Keywords.objects.all() resource_name = 'keyword-resource' filtering = {'id': ALL, 'keyword': ALL} allowed_methods = ['get', 'post', 'put', 'patch'] I want to save the comma-separated keyword in one post request from the client side. How can I post comma-separated keywords and insert them one by one into the table Keywords? Also, what would be the best way to use save() method from model or hydrate() method from tastypie resource to prepare the data to save? -
Django don't manually change the URL and go to the index.html page
I am new to Django. Let's assume my project name is mysite, and I have one app called Polls. I have 2 html in the templates file: "index.html", "df.html" Now, when I runserver, I have to manually change the URL, add "polls" after "http://127.0.0.1:8000/" to show the index.html, but I want when I click the link in the terminal, it can direct me to the index.html. I don't need to manually change the URL Thank you and any help if really appreciated! views.py def index(request): xxxx return render (request,"index.html") polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] mysite\urls.py from django.contrib import admin from django.urls import include, path from polls import views urlpatterns = [ path('polls/', include('polls.urls')), path('df/', views.df_show) ] -
Simple html form in Django
Could you please help me, I don't understand why html+css don't work as expected in Django. I use a simple form to upload two files, but it looks really ugly. index.html without id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> index.html with id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> How I can fix it? I mean get Browse... button, but with css style. -
Django Channels AsyncHTTPConsumer example
Title says it all. For the love of god, is there an example where there are routes both for 'http' and 'websocket' protocols? I'm simply trying to have (along with classic django channels websockets) an async download, and setup my asgi configuration for it, but I can't find any examples on the internet, let alone the documentation, how to have them both. It shouldn't be much of an ask, but it seems that it is. -
Forbidden (403) CSRF verification failed. Request aborted. with Gunicorn
I've created a form that includes the {% csrf_token %} but every time I submit the form it refuses it due to my domain not coming from a trusted origin. I set CSRF_TRUSTED_ORIGIN = "https://proj.com" and I even tried using @csrf_exempt to see if that would get rid of the problem but it still didn't work, the form still isn't submitting. I am using gunicorn with my django project and PostgreSQL for my database. -
django: update html dynamically when model is updated
There is a Status model with instances saved in the database. There is a view generating the html code that displays these instances to the client. Another process updates the values of the fields of these instances ('updates': read the instance from the database, change the values of some of the fields, and save the instances back to the database). I would like the html report currently displayed to the client to be updated 'live' everytime the database has been updated. I searched, but I am failing to determine the canonical way of doing this. It feels like I should use things like channels, data binding, WebsocketBinding. But the documentation (https://channels.readthedocs.io/en/1.x/binding.html) is quite difficult to follow for a beginner and I could not find any example that would help me start. It would be great, and possibly useful to many, to have a minimal example of this (not necessarily using WebsocketBinding if there are better ways of doing this) -
How can I change form field population *after* successful POST request for Class-Based-Views
I want to change the forms initial field population. Here is the catch: I want to change it for the POST request and not for the GET request. Let's say my app offers a calculation based on a body weight input. If the user inputs a body weight calculation happens with that weight, if not a default of 50 is used. So it is allowed to let the field empty. But after the calculation ran, I want to display that the value used for calculation was 50. That's why I want to populate the field with 50 after the form was initially submitted with an empty value. # forms.py class CalculatorForm(forms.Form): body_weight = forms.FloatField(required=False) def clean(self): cleaned_data = super().clean() if cleaned_data['body_weight'] is None: cleaned_data['body_weight'] = 50.0 # ideally I want to put the logic here # self.data[bpka] = 50.0 --> AttributeError: This QueryDict instance is immutable # self.fields['body_weight'] = 50.0 --> does not work # self.initial.update({'body_weight': 50.0}) --> does not work return cleaned_data I feel like the problem is that I can not reach the bound fields from the clean() method. If it is not possible within the form the logic has to go to the view I guess. Feel … -
no such table: api_user
I used from django.contrib.auth.models import User before, but now I need to switch to AbstractUser. How can I transfer the data from the previous auth_user table to AbstractUser? I followed the code from here. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100) password = models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True} # Don't return password } def create(self, validated_data): # Hash password password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance When I login to admin pages I get : no such talbe: api_user I want to use AbstractUser instead without deleting the auth_user table. -
snapchat like feature in django rest framework
In snapchat user takes a snap and can upload the taken snap to list of friends in frontend and it should be done in backend using Django rest framework instead of friends i need groups. groups should be in list in DRF user wants to upload post to different groups at same time and similar to snapchat how user can upload snaps to his friends models.py from django.db import models from django.contrib.auth.models import User class Groups(models.Model): name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='created_clusters') created_at = models.DateTimeField(auto_now=True) members = models.ManyToManyField("Members", related_name='members') post = models.ManyToManyField("Post", related_name='moments', db_column='moments') class Members(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE) groups = models.ForeignKey("Groups", on_delete=models.CASCADE, null=True, related_name='cluster_members') joined_at = models.DateTimeField(auto_now=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) post = models.FileField(upload_to='post', null=True, default='') caption = models.CharField(max_length=200, null=True) created_at = models.DateTimeField(auto_now=True) groups = models.ManyToManyField("Groups", related_name="clusters") serilizers.py there is group serializer and post serializer from rest_framework import serializers from .models import Groups, Post class GroupsSerializer(serializers.ModelSerializer): class Meta: model = Groups fields = '__all__' class PostSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Post fields = '__all__' views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from .models import Users, Groups, Post from .serializers … -
Django unexpected keyword argument "encoder"
I am using django to create a back-end for my web app and I am getting an Exception Type: TypeError at /register/ Exception Value: Field.init() got an unexpected keyword argument 'encoder'. Meanwhile there's no field like that in my views.py or serializers.py. views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.core.mail import send_mail from django.http import JsonResponse from rest_framework.generics import UpdateAPIView from rest_framework.permissions import IsAuthenticated from .serializers import UserProfileSerializer, ProfileViewSerializer, FavoriteSerializer, MessageSerializer from django.db.models import Q from django.contrib.auth.models import User from django.contrib.auth import authenticate, get_user_model, login from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.translation import gettext_lazy as _ from rest_framework import generics, permissions, serializers, status from rest_framework.response import Response from django.conf import settings from django.http import JsonResponse from rest_framework.views import APIView from .models import Favorite, ProfileView, UserProfile, Message from random import randint from django.contrib.auth.decorators import login_required from .serializers import ( LoginSerializer, UserProfileSerializer, ProfileViewSerializer, FavoriteSerializer, ) email_domain = ( ("ucc.edu.gh", "University of Cape Coast"), ("knust.edu.gh", "Kwame Nkrumah University of Science and Technology"), ("ug.edu.gh", "University of Ghana"), ("uew.edu.gh", "University of Education, Winneba"), ("umat.edu.gh", "University of Mines and Technology"), ("uds.edu.gh", "University of Development Studies"), ("upsa.edu.gh", "University of Professional Studies, Accra"), ("uenr.edu.gh", "University of Energy and Natural Resources"), ("uhas.edu.gh", … -
No hostname was supplied. Reverting to default 'localhost' - Celery Redis Django Ubuntu 22.04
I built an application with django. There are some background tasks that run using celery and redis. On windows, everything works fine. However when I deploy on Ubuntu 22.04, I get the following error in the log. settings.py # CELERY SETTINGS CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE or 'UTC' CELERY_RESULT_BACKEND = 'django-db' # CELERY BEAT SETTINGS CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dear.settings') app = Celery('dear') app.conf.broker_url = 'redis://localhost:6379/0' app.conf.result_backend = 'redis://localhost:6379/0' app.conf.enable_utc = False app.conf.update(timezone = 'Asia/Dubai') app.config_from_object(settings, namespace='CELERY') celery.conf [program:dearapi] command=/home/djangoadmin/pyapps/venv/bin/celery -A celery worker --loglevel=INFO directory=/home/djangoadmin/pyapps/dearapi/dear user=djangoadmin numprocs=1 stdout_logfile=/var/log/supervisor/celery.log stderr_logfile=/var/log/supervisor/celery.log autostart=true autorestart=true startsecs=0 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 celerybeat.conf ; ======================== ; celery beat supervisor ; … -
how to route between different pages in a website using django
I want to build a website to practice wherein i want to make a home page in which there will be two categories in a horizontal direction, lets name them "windows" and "linux" , i simply want to show text about windows when a user clicks on windows button and text about linux when a user clicks on linux button. As per my knowledge i need to create two apps called windows and linux with their respective template file and a master template file in rot folder that will work like hompage , however i am unable to put all together as im new to django. I have attached a demo picture of how i want my website to look like. I only have two html files for windows and linux app, i am unable to merge it with master template file. -
How can I use Django to transform checkboxes into radio buttons while retaining the logic of checkboxes and use them in my form?
I'd like to know how to customise a function on Django that would allow me to transform checkboxes into radio buttons, while retaining the logic of checkboxes. Let me explain: I've created a form on Django, but my form has several fields containing checkboxes with distinct behaviours depending on the field. But for the most part, the functionalities that can be observed on these checkboxes are : The ability to check and uncheck a box (normal functionality) Two checkboxes in a group of checkboxes cannot be checked simultaneously (uniqueness of checkboxes) If a checkbox encapsulates a field, then checking the box reveals the hidden field and unchecking the box or checking another box automatically hides the field encapsulated by the previous checkbox. But I haven't found any resources in the Django documentation that could help me with this task, especially as when I tried to implement the client-side logic with JavaScript/jQuery, when I submitted my form on a web page, it generated validation errors in my checkboxes, implying that the logic implemented on the client side didn't find a match on the server side, so I'm a bit at a loss, I've been working on this code for a while … -
Loading images stored on linode object storage in react
I am creating an ui for a django project and I have all my static files uploaded to a linode object storage and in django I can load images and view them with no problem but in react I fetch the url using an api from django but when I try to render it I get a 403 access forbidden. How do I set the access keys in react to grab the images? -
django rest api serialization
any hep is appreciated. What I am trying to do is build some kind of rooms booking system. this is what I did till now: from django.db import models from ckeditor.fields import RichTextField from autoslug import AutoSlugField class Room(models.Model): room_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='room_name', unique=True) room_location = models.CharField(max_length=255) room_capacity = models.CharField(max_length=50) reservation_period = models.IntegerField(default=1) item_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) room_description = RichTextField() room_image = models.ImageField(upload_to='rooms__images') def __str__(self): return self.room_name class MenuItem(models.Model): item_name = models.CharField(max_length=255) item_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return 'naam: ' + self.item_name class Reservation(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) reservation_day = models.DateField() reservation_start_time = models.TimeField() reservation_end_time = models.TimeField() first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) phone = models.CharField(max_length=255) company_name = models.CharField(max_length=255, blank=True, null=True) kvk_number = models.CharField(max_length=255, blank=True, null=True) notes = models.TextField(blank=True, null=True) def __str__(self): return self.first_name class MenuItemReservation(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField() reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE, related_name='menu_item_reservations') from rest_framework import serializers from .models import Room, MenuItem, Reservation, MenuItemReservation class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = '__all__' class MenuItemReservationSerializer(serializers.ModelSerializer): menu_item = serializers.PrimaryKeyRelatedField(queryset=MenuItem.objects.all(), source='menu_item.id') class Meta: model = MenuItemReservation fields = '__all__' class ReservationSerializer(serializers.ModelSerializer): room = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(), source='room.id') menu_item_reservations = MenuItemReservationSerializer(many=True, required=False) … -
DRF and React authentication with djoser
I how some problem with in login in django-djoser! I used django djoser in api login path('api/v1/', include('djoser.urls.authtoken')) I changed urls in authcontext and in login js dont worked authcontext.jsx and login.jsx Can you help me with this problem, signup working but login didn't open the site! Thanks before! -
Can't show image from database in django
index.html <img src="{{beat.image.url}}" class="card-img-top" alt="{{beat.name}}"> settings.py `STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'beat/media')` models.py image = models.ImageField(upload_to='images', blank=True) urls.py urlpatterns = [ path('', views.index, name='index'), path('test', views.test, name='test'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) beat.image.url not working -
How can I improve the speed and performance of database queries?
I'm currently working on a Django project where I'm encountering performance issues, especially as my application scales. To provide better context, I've included a realistic code snippet below that represents a performance-intensive section of my application: from django.db import models class Order(models.Model): # Fields and relationships... class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Product(models.Model): # Fields and relationships... def calculate_total_price(order_id): order_items = OrderItem.objects.filter(order_id=order_id).select_related('product') total_price = 0 for item in order_items: product_price = item.product.price quantity = item.quantity total_price += product_price * quantity return total_price In the above code snippet, I have an Order model that is associated with multiple OrderItems, and each OrderItem references a Product. The calculate_total_price function is used to calculate the total price for a given order by iterating over its associated OrderItems. However, as the number of OrderItems increases, the calculation becomes significantly slower. I would greatly appreciate any insights and suggestions on how to optimize this code snippet or any other general Django performance tips. Are there any specific techniques, database query optimizations, caching mechanisms, or Django features I should consider to enhance the performance of this code? Additionally, if there are any profiling tools or libraries you recommend …