Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking that model field is in url Django 4
My group project peeps and I have been stuck on this for a minute. We're making a travel web app and we have a destinations app and an attractions app. We want to check that the attraction.location is in the url so that it only displays that destinations attractions, otherwise it will show all attractions ever created, regardless of destination. We have tried multiple {% if ... in request.get_full_path %} and such and the tags we've tried are attraction.location and attraction.location.pk. Any advice would be so helpful. Here is the model and the attraction_list.html snipped that we are trying to put it in models.py class Attraction(models.Model): location = models.ForeignKey( Destination, on_delete=models.CASCADE, ) name = models.CharField(primary_key=True, max_length=255) description = models.TextField(blank=False) address = models.TextField() rating = models.IntegerField( blank=False, validators=[MaxValueValidator(5), MinValueValidator(1)] ) tags = models.TextField() numberReviews = models.IntegerField(default=1) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name def get_absolute_url(self): return reverse("attraction_detail", kwargs={"pk": self.pk}) attraction_list.html {% for attraction in attraction_list %} {# trying to use if in statement to check if attraction.location is in the full path #} <div class="card"> <div class="card-header"> <span class="fw-bold"> <a href="{{ attraction.get_absolute_url }}">{{ attraction.name }}</a> </span> &middot; <span class="text-muted">by {{ attraction.author }} | {{ attraction.date … -
Json nested object array data request post method in Django
My JSON nested object array Input: { "rawdata": [ { "type": "Host_HostParameter", "cmdbid": "CMDB3248972067", "name": "hostname", "product": "hostproduct", "modified_at": "2023-12-11T11:59:34", "modified_by": "person_name", "assetinfo": { "description": ["description1","description2"], "status": ["Deployed"] } } ] } In Django models.py from django.db import models from django.core.validators import RegexValidator # Create your models here. class Host(models.Model): cmdbid = models.CharField(primary_key=True, max_length=15, validators=[RegexValidator('^CMDB[0-9]{11}','invalid CMDB ID')]) name = models.CharField(max_length=80) ## by default blank=False, null=False product = models.CharField(max_length=50) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) class HostParameter(models.Model): fk = models.ForeignKey(Host, on_delete=models.CASCADE) ##fk is value cmdbid parameter_section = models.CharField(max_length=40) parameter = models.CharField(max_length=80) parameter_index = models.IntegerField() value = models.CharField(max_length=200, null=True) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) In Django serializers.py from rest_framework import serializers from django.conf import settings from .models import Host,HostParameter """ ###Host### class HostSerializer(serializers.ModelSerializer): class Meta: model = Host fields = "__all__" ###HostParameter### class HostParameterSerializer(serializers.ModelSerializer): class Meta: model = HostParameter fields = "__all__" In Django views.py #####Host#### class HostViewFilter(FilterSet): """ Filter for Host """ class Meta: model = Host fields = '__all__' class HostView(viewsets.ModelViewSet): """ GET... Will list all available Host POST... Will create a new Instance parameters entry PUT... Will update a existing Instance parameters entry """ permission_classes = [DjangoModelPermissions] queryset = Host.objects.all() serializer_class = HostSerializer filter_class = HostViewFilter http_method_names = … -
Django-htmx: Understanding trigger_client_event from the django_htmx module
The other day someone suggested me to start using the django_htmx module to boost my htmx experience in the framework. One of the functionalities I'm more interested on is the trigger_client_event response modifier that seems to be able to trigger an event in the client. But I can't get it to work and the documentation offers no example of the client side code. Here's the code I'm using in the back-end and the client: from django.views import View from django_htmx.http import retarget, reswap, trigger_client_event class HxFormValidationMixin(View): hx_retarget = 'this' hx_reswap = 'innerHTML' hx_event = '' def form_invalid(self, form): response = super().form_invalid(form) return reswap(retarget(response, self.hx_retarget), self.hx_reswap) def form_valid(self, form): response = super().form_valid(form) return trigger_client_event(response, self.hx_event, {}) document.addEventListener('modal-hide', () => { document.querySelector('#assistantStudentModal').modal('hide'); }); Sadly the event is not being handled. As a note, the first code is a Mixin meant to be reused, in the view were I use it the hx_event is set to 'modal-hide'. Also, I guarantee that the #assistantStudentModal exists and its visible when the event should ocurr. What I'm doing wrong? Someone knows how to catch the event in the client? -
Django Function after action decorator is being ignored
I have this View in django and when I do the post request it ignores the logic in my function completely and will do a post and then return the object, I am wondering how I can have it follow my logic from django.utils.translation import ugettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from rest_framework import mixins, serializers, viewsets from rest_framework.viewsets import ModelViewSet from apps.units.models import Unit from apps.api.mixins import DestroyModelMixin from apps.api.v1.decorators import action from apps.leads.models import Leads from .serializers import LeadSerializer from apps.api.v1.units.serializers import UnitSerializer class LeadsViewSet( mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin, DestroyModelMixin, ): serializer_class = LeadSerializer queryset = Leads.objects.all() @action(methods=["POST"], detail=False,) def create_lead(self, request, pk=None, *args, **kwargs): try: date = request.body.get("date") user_id = request.body.get("user_id") unit_id = request.body.get("unit_id") existing_lead = self.queryset.filter(user_id=user_id, unit_id=unit_id).exists() if existing_lead: raise serializers.ValidationError(_("Lead already exists")) Leads.objects.create( user_id=user_id, unit_id=unit_id, date=date ) return ({"message":"Lead Created Succesfully"}) except Exception as e: raise serializers.ValidationError(_("Lead not created")) -
How to add translation support to Django constants?
I have a Django application with some dictionaries defined in constants.py. The values in the dictionary represent user-readable labels, and I want to add translation support, so Django i18n feature than auto-translate them based on locale. So I added to the top of my constants.py: from django.utils.translation import gettext_lazy as _ and then applied it like: { "code": _("some name to be translated"), .... } That seems to have worked somewhat, put I'm running into problems with Celery and multi-processing support, or anything that tries to import my models in anything but the most vanilla manner. Specifically, when trying to do any kind of multi-processing, Django now throws the error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. which is itself caused by a different error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. and the traceback for that starts at my use of gettext_lazy in constants.py. So clearly, something I'm doing is not copacetic. Is there a best practice to applying translation support to constants in Django? -
Django - Left join parent and child tables?
I am new to Django. I am trying to figure out how to do a left join with the least number of database queries. I have searched stackoverflow and have spend days trying to figure this out. I have looked into using .select_related, I have tried a raw query and tried to see if it could be done with Q, but I still cannot figure this out. I would like to retrieve all States and linked Cities if any listed, Models.py class State(models.Model): name = models.CharField(max_length=25) abbreviation = models.CharField(max_length=2) def __str__(self): return str(self.id) class City(models.Model): name = models.CharField(max_length=25) population = models.IntegerField() state = models.ForeignKey(State, related_name="cities", on_delete=models.CASCADE) def __str__(self): return str(self.id) State Table ID Name Abbreviation 1 Texas TX 2 California CA 3 Illinois IL City Table ID Name Population State 1 Los Angeles 3769485 2 2 Dallas 1259404 1 3 Houston 2264876 1 Desired result |-------------- State -------------|----------------- City -------------------| ID Name Abbreviation ID Name Population State 1 Texas TX 2 Dallas 1259404 1 1 Texas TX 3 Houston 2264876 1 2 California CA 1 Los Angeles 3769485 2 3 Illinois IL Problem 1 (Using .select_related): cities_states = City.objects.all().select_related('state').order_by('state_id') Using .select_related does not give me any States (e.g. Illinois) that … -
Don't set language cookie in Django
We're trying to avoid setting the Django language cookie, as this is the only cookie our site uses, and we want to avoid the legal liability of setting cookies. But I can't seem to find a way to prevent Django from setting this cookie. -
code=H14 desc="No web processes running" method=GET path="/"
im deployed my app Django in Heroku but, the application not works, it show me that error, this is my repo https://github.com/zlcosio21/MoralGamesWeb the code of the application, the files enter image description here I tried changing the procfile and it doesn't work either. -
Does docker compose up -d --build clear db?
I am using a docker compose for my django app and postgres db. when I have a new migration docker compose up -d --build clears my data in db. I want to know what is wrong? --build may clear ? my yaml file: version: "3.9" services: db: image: postgis/postgis:14-3.2 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=db - POSTGRES_USER=user - POSTGRES_PASSWORD=123456 ports: - "5434:5432" web: restart: always build: . command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "7000:8000" environment: - POSTGRES_NAME=db - POSTGRES_USER=user - POSTGRES_PASSWORD=123456 - UPLOAD_LOCATION_MEDIA=/srv/app/cdn/media - UPLOAD_LOCATION_IMAGE=/srv/app/cdn/image depends_on: - db -
( AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I have this view in my django project class OrdersGranularity(generics.ListAPIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = GetOrdersSerializer def get(self, request, *args, **kwargs): granularity = self.request.query_params.get('granularity', 'day') if granularity == 'month': return self.get_orders_by_month() else: return self.get_orders_by_day() def get_orders_by_day(self): start_date_str = self.request.query_params.get('start_date') end_date_str = self.request.query_params.get('end_date') operator_pk = self.request.query_params.get('pk') statuses = self.request.query_params.get('status') queryset = Order.objects.all().order_by('-created_at') if start_date_str and end_date_str: try: start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() queryset = queryset.filter(created_at__date__range=[start_date, end_date]) except ValueError: return Response({'error': 'Invalid date format'}, status=status.HTTP_400_BAD_REQUEST) if operator_pk and operator_pk.lower() != 'none': queryset = queryset.filter(operator=operator_pk) if statuses: statuses_list = statuses.split(',') queryset = queryset.filter(status__in=statuses_list) serializer = self.get_serializer(queryset, many=True) return Response({'results': serializer.data}) # Provide a simple structure def get_orders_by_month(self): start_date_str = self.request.query_params.get('start_date') end_date_str = self.request.query_params.get('end_date') operator_pk = self.request.query_params.get('pk') statuses = self.request.query_params.get('status') queryset = Order.objects.all() if start_date_str and end_date_str: try: start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() queryset = queryset.filter(created_at__date__range=[start_date, end_date]) except ValueError: return Response({'error': 'Invalid date format'}, status=status.HTTP_400_BAD_REQUEST) if operator_pk and operator_pk.lower() != 'none': queryset = queryset.filter(operator=operator_pk) if statuses: statuses_list = statuses.split(',') queryset = queryset.filter(status__in=statuses_list) queryset = queryset.annotate( month=TruncMonth('created_at') ).values('month').order_by('month') serializer = self.get_serializer(queryset, many=True) if not serializer.data: return Response({'results': []}) return Response({'results': serializer.data}) when I send request to this endpoint like this http://localhost:8000/dashboard/OrdersGranularity/?granularity=day&start_date=2023-01-01&end_date=2023-12-31&status=done it works but when I … -
Choose a directory from user pc with django
I'm developing a django application (my first time using it) where I need to store a user directory on the database, for that I've extended the user model to add one charfield: from django.db import models from django.contrib.auth.models import User class Directory(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) xml_directory = models.CharField() That directory will be later used to iterate between its files. My problem now is that I cant find how to make the "Alterar" button to open a dialog box for the user to choose the directory. Does anyone have an idea of how I can achieve that? <!DOCTYPE html> {% extends 'base.html' %} {% block title %}XML{% endblock title %} {% block pagename %}Processar XML{% endblock %} {% block content %} <form action="{% url "save_directory" %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="xml_directory">Local dos Arquivos XML</label> <input class="form-control col-6" readonly type="text" id="xml_directory" name="xml_directory" placeholder="{{diretorio_xml}}"></input> <button class="btn btn-primary" >Alterar</button> <button class="btn btn-success" type="submit">Salvar</button> </div> </form> {% endblock %} </html> -
Django admin redirect issue (unintended redirect to '.../?e=1')
I'm trying to write a simple calendar app called 'cal' in django and I modify the event (model) registration for visualize the calendar also in the changelist_view (/admin/cal/event/). I wrote two functions (prev_month and next_month) that return a url with two parameters with the month and the year ('?month={month}&year={year}') to be displayed. When i go to this url, in server side, the page is rendered, but instead of sending the HTML it redirects to this URL /admin/cal/event/?e=1 and the month doesn't change. #admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): def formatted_date(self, obj): return obj.event_date.strftime("%Y-%m-%d") formatted_date.short_description = 'Formatted Date' def changelist_view(self, request, extra_context=None): if extra_context is None: extra_context = {} year = int(request.GET.get('year', datetime.today().year)) month = int(request.GET.get('month', datetime.today().month)) d = date(year, month, day=1) cal = CalendarAdmin(d.year, d.month) html_cal = cal.formatmonth(withyear=True) extra_context['calendar'] = mark_safe(html_cal) extra_context['prev_month'] = prev_month(d) extra_context['next_month'] = next_month(d) return super().changelist_view(request, extra_context=extra_context) def prev_month(d): first = d.replace(day=1) prev_month = first - timedelta(days=1) month = str(prev_month.month) year = str(prev_month.year) return f'month={month}&year={year}' def next_month(d): days_in_month = calendar.monthrange(d.year, d.month)[1] last = d.replace(day=days_in_month) next_month = last + timedelta(days=1) month = str(next_month.month) year = str(next_month.year) return f'month={month}&year={year}' CalendarAdmin is a simple class to generate a calendar. I've tried everything, I modify the CalendarAdmin class, the EventAdmin class, the deafault … -
Unable to import oauth2_provider.contrib.rest_framework in view ,after installing django-oauth-toolkit djangorestframework
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'rest_framework', 'corsheaders', 'oauth2_provider', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ) } Please help to fix the issue ,as I unable to use from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope in my view -
Using multiple variable in a Django HTML page?
Essentially I need to pass a few variables into the same HTML page in Django, yet I can only seem to register one. Here is the View for the variable I want to use: @login_required def dtasks_24(request): usern = str(request.user) today = datetime.now().date() tomorrow = today + timedelta(days=1) tasks_due_tomorrow = Task.objects.filter(assigned_members__username="@pjj",due_date__in=[today, tomorrow]) dtasks_24 = tasks_due_tomorrow .count() return render(request, 'dashboard.html', {'dtasks_24': dtasks_24}) Here is how I am using it in the dashboard.HTML file: {{ dtasks_24 }} Here are my URLs: path('dashboard/', views.dashboard, name='dashboard'), path('dashboard/', views.dtasks_24, name='dtasks_24'), the variable dashboard work but dtasks_24 does not, I do not have a HTML file for dtasks_24. Thank you for any help -
Celery Flower not sending task status from API call
For a very long time we'd been using Celery and flower to handle tasks and have a process that starts these tasks with a call to a flower endpoint. Like so http://flower.com/api/task/send-task/task_name This used to give back both a task-id and a state value (specifically Pending). After upgrading from Celery 4.3.0 --> 5.3.4 and Flower 0.9.2 --> 1.2.0 we no longer get that state value back. This is being done in conjunction with django btw on python 3.8. Everything else in the process works fine, tasks are executed and run normally and the state is properly reported in the celery dashboard. It's just that this initial call to the API is missing this state value. Based on the code presented in the flower git repo it looked like the send-task would look for a backend initialized for the result, otherwise it won't attach the state. However our backend appears to be initialized without issue, as both the logs confirm the connection as well as the db having up to date records of task executions. Here is the celery config from the settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 57600} CELERYD_PREFETCH_MULTIPLIER = 1 CELERYD_TASK_TIME_LIMIT = 57600 CELERY_ACKS_LATE = … -
Deep Learning Model calling through FAST API
Is it possible to call a deep learning model which is working on several GBs of data to be called through an api which is made by Fast API? Or would DjangoREST or Flask be a better approach? -
How to prevent race condition while working with sessions?
I’m working on an e-commerce website with a cart and products. A product’s primary key is added to the user’s session data in a dictionary 'cart_content'. I successfully reproduced a race condition bug by triggering a click() twice with an amount of product that will sold out for the next purchase. So the two requests increment twice the cart but there is not enough stock. How can I prevent race condition to happen like the example given above or in a multi-user case ? Does there is for example some sort of lock system that prevent add_to_cart() from being executed asynchronously ? core/models.py : class Product(models.Model): … number_in_stock = models.IntegerField(default=0) @property def number_on_hold(self): result = 0 for s in Session.objects.all(): amount = s.get_decoded().get('cart_content', {}).get(str(self.pk)) if amount is not None: result += int(amount) return result … cart/views.py : def add_to_cart(request): if (request.method == "POST"): pk = request.POST.get('pk', None) amount = int(request.POST.get('amount', None)) if pk and amount: p = Product.objects.get(pk=pk) if amount > p.number_in_stock - p.number_on_hold: return HttpResponse('1') if not request.session.get('cart_content', None): request.session['cart_content'] = {} if request.session['cart_content'].get(pk, None): request.session['cart_content'][pk] += amount else: request.session['cart_content'][pk] = amount request.session.modified = True return HttpResponse('0') return HttpResponse('', status=404) cart/urls.py: urlpatterns = [ … path("add-to-cart", views.add_to_cart, name="cart-add-to-cart"), … -
Cannot login on my website with a user I create in django admin
I have a login and signup page, where a user that signs up is able to login and i can view this user in the admin portal as shown in the screenshots below: Example User created through signup page: Username=usertest Password=pass123 Signup page Signed up user visible in admin portal (note: password is hashed) However, when i create a user in admin portal I cannot login with that user in login. This may be due to the password that is being stored as it is not hashed when viewing admin portal-not too sure: Example User created through django admin portal: Username=usertest2 Password=pass1234 User created via admin portal (note: password is not hashed) Login says invalid despite user present in admin view I have tried to have a look and think it might be the password is not hashed when creating a new user in admin portal and so when login is compared this might be causing the issue- not too sure. Below are my codes, I can share further code that can help solve this too: 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) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile-images") date_of_birth = models.DateField(null=True, blank=True) … -
How do i get these crsf token for a drf api without frontend?
Hi I am new to Django Rest frameworks and I am making a api for a mobile app which will make post request to the Backend so the thing is I am getting a response from the request which is { "error": "CSRF token missing" } And I tried to see BardAi and ChatGPT they said that it would only work if I have a front end framework dealing with these cookies so is that a solution to get the token without using the decorator which would exempt the token all in itself. I would like source code and any solutions. -
How to render in real-time one of the fields of the Django model?
I already set up the connection between the server side which are the asgi.py, consumers, and routing, that is already listening to client side using javascript. But I don't know how to render out, in real time, the field in that one model to my javascript that'll will be shown in HTML. I'm not trying anything for now since I do not know where to start, and what to do. But all I want to achieve is to render that one field from the model through the HTML in real time. -
Running django project using pm2 and gunicorn fails with syntax error I cant fix
I'm following these guides: https://david.dev/deploying-django-with-pm2-and-gunicorn https://www.umutsagir.com/how-to-properly-serve-python-apps-with-pm2-and-gunicorn-on-any-port-and-any-server/ and trying to get my django project to run using gunicorn and pm2. My ecosystem.config.js looks like this: module.exports = { apps: [ { name: 'projectname-django-live', script: '/root/.cache/pypoetry/virtualenvs/projectname-n-gjsKBO-py3.10/bin/gunicorn', args: [ '--chdir=/var/www/projectname/projectname', 'projectname.wsgi:application', '--bind=0.0.0.0:3200', // Replace with your desired port '--workers=1', // Adjust the number of workers based on your server's capabilities '--threads=3', // Adjust the number of threads based on your server's capabilities // Add any other Gunicorn options here ], error_file: '/var/log/projectname_live/pm2_django_err.log', out_file: '/var/log/projectname_live/pm2_django_out.log', }, ], }; The projectname is three times in the path, because the location of the wsgi.py file is /var/www/projectname/projectname/projectname/wsgi.py The error I get is: root/.cache/pypoetry/virtualenvs/projectname-n-gjsKBO-py3.10/bin/gunicorn:2 # -*- coding: utf-8 -*- ^ SyntaxError: Invalid or unexpected token at internalCompileFunction (node:internal/vm:73:18) at wrapSafe (node:internal/modules/cjs/loader:1178:20) at Module._compile (node:internal/modules/cjs/loader:1220:27) at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) at Module.load (node:internal/modules/cjs/loader:1119:32) at Module._load (node:internal/modules/cjs/loader:960:12) at Object.<anonymous> (/usr/local/share/.config/yarn/global/node_modules/pm2/lib/ProcessContainerFork.js:33:23) at Module._compile (node:internal/modules/cjs/loader:1256:14) at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) at Module.load (node:internal/modules/cjs/loader:1119:32) and I'm not sure how to fix this. I thought that perhaps I need to set the interpreter in the config file. Not sure, but since the gunicorn path is the full virtualenv path, it should be fine, right? Help pls. Alan. -
Multiform nested data
Hey there i am trying to serialize the multiform nested data but i have tried everything but nothing works for me and also i did not get any kind of help from internet. enter image description here and i am getting data from frontend like that: <QueryDict: {'product_name': ['aa'], 'category': ['electronics'], 'description': ['aaa'], 'price': ['12'], 'inventory': ['[{"size":"Small","color":"Black","quantity":"4"}]'], 'images': [<InMemoryUploadedFile: Screenshot 2023-11-16 131611.png (image/png)>]}> please give some solution I have tried different libraries for parsing nested multiparse data but did not get a solution -
AWS Django NGINX timeout and async errors
I have a view in which I try to upload an excel sheet via a form. The excel that I upload isn't that big but the processing of the data in that excel is causing nginx time out issues resulting in a 502 Bad Gateway error. I do not have this problem when testing locally but it pops up on AWS EC2 when testing it on that environment. I increased the time out periods in nginx via (as suggested here): proxy_read_timeout 300s; proxy_connect_timeout 300s; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; And that did improve things somewhat since I can see more results but it was not sufficient. Curiously it timed out again before the 300s were up. Incidentally, if it used all 300s it should complete the process. It was also suggested I use async to make the processing independent of the upload process and that it run the processing in the background. However in attempting I keep running into this error: "object HttpResponseRedirect can't be used in 'await' expression" This error occurs when I try to load the page even before I try to upload the excel file which is the only time I have a redirect, which … -
Why aren't media files autogenerated in Django?
So i create same project which accepts input from the user in the form of an image. I followed Django step documentation and this. The result I got was correct, I received input from the terminal if the 'POST' method was successful by returning status code 200. But why is the media folder in the root directory not created? I've changed the settings.py with this code cartoon/views.py from django.shortcuts import render, redirect from django.http import HttpResponseServerError, HttpResponse from .forms import CartoonImageForm import cv2 import numpy as np from django.http import JsonResponse def cartoon (request): return render(request, 'cartoon/cartoon.html') def image (request): if request.method == 'POST': form = CartoonImageForm(request.POST, request.FILES) if form.is_valid (): form.save() return redirect('success') else: form = CartoonImageForm() return render(request, 'cartoon/cartoon.html', {'form': form}) def success(request): return HttpResponse('successfully uploaded') This urls.py # cartoon/urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import cartoon, image app_name = 'cartoon' urlpatterns = [ path('cartoon/', cartoon, name='cartoon_page'), path('result/', image, name='cartoon_result') ] ## MEDIA if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) cartoon/forms.py from django import forms from .models import CartoonImage class CartoonImageForm(forms.ModelForm): class Meta: model = CartoonImage fields = ['image_upload'] directory root settings.py # Build paths inside the project like this: … -
Model property object not showing up
I try to calculate the average rating for my user. I triede to define property so it calculates and shows automatically. Models.py class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=40, unique=True, default='undefinedusername') email = models.CharField(max_length=255, unique=True,null=True,blank=True) @property def average_rating(self): return self.usercomments.all().aggregate(Avg('rate')).get('rate__avg', 0.00) class UserComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='usercomments_author') rate = models.IntegerField(default='0') Serializers.py class UserSerializer(serializers.ModelSerializer): rating_count = serializers.SerializerMethodField(read_only=True) usercomments_set = UserCommentSerializer(source='usercomments', required=False, many=True) class Meta: model = User fields = '__all__' def get_rating_count(self, language): return language.usercomments.count() def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('id') == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') Here is my result: { "count": 1, "next": null, "previous": null, "results": [ { "id": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "usercomments_set": [ { "id": "61c5b21e-3456-4a13-83c4-4557cd621af6", "rate": 4, "profile": "8b0efd7e-06ac-4d57-a347-e9ffe79c3c31", "author": "f474d116-ec1d-498b-a166-7af3fa8cfd59" } ], "rating_count": 1, "username": "undefinedusername", "email": "testmail@gmail.com", }, } Everything else except average_rating shows up. What is the issue?Where did I make the mistake?