Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Lost connection to MySQL server during query
I have a very long await im my django rest framework project (up to 30 minutes) for a response from a websocket stream. I am waiting for a user reply in the websocket (chat). I then want to save a instance of a model class to the database. However I get an error "django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')" if the user in not responding with in minutes. I cant change the logic since I need to monitor the websocket connection where the user is replying. I tried to increase the connection duration by setting CONN_MAX_AGE: 1800 in my settings.py but it seems that this doesnt do the trick. Thanks -
How to resolve “The selected OTP device is not interactive” error while logging into Django administration?
enter image description here Here's the SS of my django login. I'm trying to implement OTP for a site I'm running locally. I have filled in my superuser credentials in here, but I'm facing issues in the OTP section. When I click on to select an OTP device, It doesn't show anything excpet for an empty field, if I click that empty field and proceed to click "Get OTP Challenge", I'm displayed "The selected OTP device is not interactive" text. I'm running it on my PC. What should I make interactive? Excuse me for I am a total noob in this work. This is part of a virtual experience program by JPMC. I'm expected to complete this step and access a QR Code present after this page. -
django orm optimize the query
I need query in django orm to clubs list endpoint. with clubs where user is the club owner, or user is Tournament Referee (with empty end_date, or the end_date is more recent than now). I have models: class User(AbstractBaseUser): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) ... class Club(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) owner = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) class Tournament(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) club = models.ForeignKey(Club, on_delete=models.CASCADE) class TournamentReferee(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, related_name='tournament_referee') user = models.ForeignKey(User, on_delete=models.CASCADE) end_date = models.DateTimeField("access expire date", blank=True, null=True) I created my query like this, but maybe there is a better way to do it with a single query? def get_queryset(self): if self.request.method == 'GET': now = datetime.datetime.now() referee_clubs_list = TournamentReferee.objects.filter(Q(user=self.request.user), (Q(end_date__isnull=True) | Q(end_date__gte=now))).values_list('tournament__club_id') return Club.objects.filter(Q(owner=self.request.user) | Q(id__in=(referee_clubs_list))) return super().get_queryset() -
Why aren't my registered users showing on the Django admin panel?
I am relatively new to django. I am developing a user registration system. I have tried testing the user registration but the details aren't getting shown in the admin panel.I can manually add someone form the backend but when they use the form, and submit, it doesn't show in the admin panel for users and I don't get any errors. I have tried checking for the method in the form, I also tried changing the html method from "post" to "POST" but it didn't work and any errors in views or urls but can't seem to find where I am wrong. This is my views from django.shortcuts import render from userauths.forms import UserRegisterForm # Create your views here. def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() else: form = UserRegisterForm() context = { 'form':form, } return render(request, "userauths/register.html", context) This is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from userauths.models import User class UserRegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'email'] Here is my html form <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Register</button> </form> -
Django Rest Framework Serialiser Error -> Fields Not Found
I am fetching data from an api in my django backend and serializing the data to get the required fields and sending that to the frontend The seriliaser class EventSearchOutputSerialiser(Serializer): date_time = DateTimeField(source='dates.start.dateTime') icon = URLField(source='images.0.url', allow_null=True) event = CharField(source='name') genre = CharField(source='classifications.0.genre.name') venue = CharField(source='_embedded.venues.0.name') So basically here I am trying to pull out the data from the nested fields. An example of the fetched data which will be passed for serialisation. This data is fetched from ticketmaster api. [ { "name": "Utah Jazz vs. Phoenix Suns", "type": "event", "id": "Z7r9jZ1AdJ9uz", "test": false, "url": "https://www.ticketmaster.com/event/Z7r9jZ1AdJ9uz", "locale": "en-us", "images": [ { "ratio": "3_2", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_RETINA_PORTRAIT_3_2.jpg", "width": 640, "height": 427, "fallback": false }, { "ratio": "3_2", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_ARTIST_PAGE_3_2.jpg", "width": 305, "height": 203, "fallback": false }, { "ratio": "4_3", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_CUSTOM.jpg", "width": 305, "height": 225, "fallback": false }, { "ratio": "16_9", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_RETINA_PORTRAIT_16_9.jpg", "width": 640, "height": 360, "fallback": false }, { "ratio": "3_2", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_TABLET_LANDSCAPE_3_2.jpg", "width": 1024, "height": 683, "fallback": false }, { "ratio": "16_9", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_RECOMENDATION_16_9.jpg", "width": 100, "height": 56, "fallback": false }, { "ratio": "16_9", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_TABLET_LANDSCAPE_LARGE_16_9.jpg", "width": 2048, "height": 1152, "fallback": false }, { "ratio": "16_9", "url": "https://s1.ticketm.net/dam/a/a01/dc895acf-863e-4f90-9316-98302e99fa01_1761311_RETINA_LANDSCAPE_16_9.jpg", "width": 1136, "height": 639, "fallback": false }, { "ratio": "16_9", "url": … -
How can I submit several forms together in one time with JavaScript?
Hello (I am a Django developer),I want to submit some forms in html together in one time by JavaScript. when the button clicked, I want to submit all of them. Please guide me. Thank you. Submit some forms together in one time by JavaScript. -
HTMX & Django: Using HMTX across multiple Class Based Views
Desired Outcome: I am attempting to implement a UX flow with htmx and Django, where the user first selects a date, then a timeslot (determined based on the date), then a ticket (availability calculated based on date and time) and then inputs any special requests. Forms and elements are dynamically rendered without page refresh up to this point. User can then proceed to the next step (booking summary) which is on a different page. At each stage (i.e. each post in my view) I am saving important variables in the session. These are the variables posted via htmx and will be used later to create a model instance. Problem: When I get to the final view, the post request returns a blank page and the url does not change. It also seems like it is initiating the post request from my original view once again (since the selected date variable is printed again in console as None whereas prior to this, it is the date selected from the SelectDateForm). Context: The project is for an activity booking website. This flow is how the user books a particular activity. It works up until the final view in that flow (SpecialRequestsView), and … -
Django Auth Login Form Not Working - Clicking Button Not Attempt To Submit
Attempting to leverage the Django Authentication System. I cannot get the log in form to attempt a submission. 60 Second Video of Issue Its like the button is not being clicked I have added the django.contrib.auth.urls to the root URL Conf, added a created a template with a form to a registration/login.html in templates. I get the template and form to render, but the form fails to submit, like the button is not being clicked. Not a rejected login, but complete non-action. The other templates and forms associated with the django.contrib.auth.urls such as password_reset, are working as expected. {% extends "layouts/base-layout.html" %} {% load static %} {% block TITLE %}Login{% endblock TITLE %} {% block MAIN %} <!-- Sign In Start --> <div class="container-fluid"> <div class="row h-100 align-items-center justify-content-center" style="min-height: 100vh;"> <div class="col-12 col-sm-8 col-md-6 col-lg-5 col-xl-4"> <div class="bg-secondary rounded p-4 p-sm-5 my-4 mx-3"> <div class="d-flex align-items-center justify-content-between mb-3"> <h3 class="text-primary"><i class="fa fa-user-edit me-2" aria-hidden="true"></i> <span id="learnosity">Learnosity</span> Support<br/> Engineer Log-In</h3> </div> {% if form.errors %} <div class="message-container"> <div class="alert alert-danger d-flex align-items-center" role="alert"> <i class="fa-solid fa-circle-xmark"></i> <div> <p>Invaild Inputs</p> </div> </div> </div> {% endif %} {% if next %} <div class="alert alert-danger d-flex align-items-center" role="alert"> <i class="fa-solid fa-triangle-exclamation fa-xl"></i> <div> … -
Regarding filters in django
<div class="project-container"> <div class="project-header"> <div class="status-container"> <h1 class="project-header-text">{{ project_instance.projectTitle }}</h1> <select id="select1" name ="status" onchange="getOption()"> <option value="#">Search for status</option> <option value="Show all" selected>Show all</option> <option value="I">In progress</option> <option value="C">Completed</option> <option value="R">Submitted for Review</option> </select> </div> <div class="progress-create-btn"> <a href="./project_details.html"><button class="project-header-btn btns">View Project Details</button></a> <a href="./progress.html"><button class="project-header-btn btns">View Progress</button></a> <a href="{% url 'create-task' project_id=project_instance.projectID %}"><button class="project-header-btn btns">Create Task</button></a> <!-- <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Status.." title="Type in a name"> --> </div> </div> <div class="project-body"> <table class="main-table" id="maintable"> <thead> <th>Tasks</th> <th>Status</th> <th>View task</th> </thead> <tbody> {% for task in task_instance %} <tr class="table-row"> <td class="table-data">{{ task.taskTitle }}</td> <td class="table-data"> <h3 class="label-tag"> {% if task.status == 'I' %} Pending {% elif task.status == 'C' %} Completed {% elif task.status == 'R' %} Submitted for Review {% else %} Unknown {% endif %} </h3> </td> <td class="table-data"> <a href="{% url 'view-tasks' project_id=project_instance.projectID %}"> <button class="button-tag btns">View</button> </a> </td> </tr> {% empty %} <tr class="table-row"> <td class="table-data" colspan="4">No tasks to show</td> </tr> {% endfor %} </tbody> </table> </div> This is my html code function myFunction(filter) { var table, tr, td, i, txtValue; // input = document.getElementById("myInput"); // filter = input.value.toUpperCase(); filter=filter.toUpperCase(); if(filter=="SHOW ALL"){ filter=""; } table = document.querySelector(".main-table"); tr = table.getElementsByTagName("tr"); for (i = … -
create multiple objects in model serializer create method
I need the below DRF API View to list and create Withdraw records in my Django project. class WithdrawListCreateAPIView(PartnerAware, WithdrawQuerySetViewMixin, generics.ListCreateAPIView): permission_classes = (TokenMatchesOASRequirements,) required_alternate_scopes = { "GET": [[OTCScopes.WITHDRAW_READ]], "POST": [[OTCScopes.WITHDRAW_CREATE]], } def get_serializer_class(self, *args, **kwargs): if self.request.method == "POST": return WithdrawCreateSerializer return WithdrawSerializer def initial(self, request, *args, **kwargs): super().initial(request, *args, **kwargs) self.get_partner_info() def perform_create(self, serializer): serializer.save(partner=self.partner, created_by=self.request.user) My API construction must be for a single record, but it is possible that this amount may be greater than a specific amount called SETTLEMENT_MAX_AMOUNT, and I have to break it down to more than one Withdraw record and also I must create a separate record for each one, and I should return all these records that have been created in one list to the user.Here is the related serializer I've implemented for this case: class WithdrawCreateSerializer(serializers.ModelSerializer): target_uuid = serializers.UUIDField(write_only=True) def validate_target_uuid(self, value): partner = self.context["view"].partner try: target = WithdrawTarget.objects.get(active=True, uuid=value, partner=partner) except WithdrawTarget.DoesNotExist: raise serializers.ValidationError("Target does not exist for the current partner.") return target.uuid def create(self, validated_data): target_uuid = validated_data.pop("target_uuid") partner = self.context["view"].partner target = WithdrawTarget.objects.get(uuid=target_uuid, partner=partner) amount = validated_data["amount"] num_withdrawals = amount // SETTLEMENT_MAX_AMOUNT remaining_amount = amount % SETTLEMENT_MAX_AMOUNT withdrawals = [] for _ in range(num_withdrawals): withdraw_data = { "target": … -
Django admin panel redirects and URL issues: Incorrect paths in admin sites
I have a Django app for a REST API, and I also need to use the Django admin for some tasks. When I run the app locally and try to access the admin panel with the URL http://localhost:8000/admin, Django redirects me to http://localhost/localhost/admin. Also, when I try to access the login panel as http://localhost:8000/admin/login, I can see a valid login page. However, after clicking on 'Log In', a POST request is sent to http://localhost:8000/lo/admin/login/. I checked how HTML files are created for Django admin. I found a variable, app_path, that is passed to the template for creating the login page. The value for this variable is assigned in /usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py as app_path': request.get_full_path(). I created an endpoint to test the values returned from the get_full_path() function. When I call the endpoint http://localhost:8000/api/getadminurls, the value from get_full_path() is http/api/getadminurls. From all of this, I came to the conclusion that Django is not able to find the correct values that should be filled into those templates, but I was not able to find how to fix this. -
Tailwind css is not being served in Django App
I've been working on this Tailwind+Django project and it was working fine. Now it's not serving css. I've run the commanands py manage.py runserver and py manage.py tailwind start and there's no problem on servers. here is Settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'authen.CustomUser' TAILWIND_APP_NAME = 'theme' INTERNAL_IPS = [ "127.0.0.1", ] NPM_BIN_PATH = r"C:\Program Files\nodejs\npm.cmd" urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("__reload__/", include("django_browser_reload.urls")), path('',include('authen.urls')), path('rental/',include('rental.urls')), path('roommate/',include('roommate.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Tailwind.config.js module.exports = { content: [ '../templates/**/*.html', '../../templates/**/*.html', '../../**/templates/**/*.html', ], theme: { extend: {}, }, plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), require('@tailwindcss/line-clamp'), require('@tailwindcss/aspect-ratio'), ], } here is the project structure Thanks for your time. if any further information is needed please ask. -
Get data from model in django with ajax
I have a django website which needs interaction through ajax. One of my pages includes a checkbox and I would like the data displayed on the client to depend on the state of my checkbox. Here is my view.py : ... def sales_view(request): dataModel = DataModel() return state_view(request, dataModel.m_bp.m_sales.m_name, sales_html) ... And my template sales_html.py (not a .html file as I use airium : from airium import Airium from contextlib import contextmanager from ..DataModel import DataModel @contextmanager def sales_html(a: Airium, dataModel: DataModel): # Page Heading with a.div(klass="d-sm-flex align-items-center justify-content-between mb-4"): a.h1(klass="h3 mb-0 text-gray-800", _t=dataModel.m_bp.m_sales.m_name) a.input(type = "checkbox", id = "yearMonthToggle", onclick = "myFunction()") a.script(src = "{% static 'src/js/test.js' %}", type = "text/javascript") # Get data from the model. myData = dataModel.getMyData() ... # Display the main ItemsGroups. a.div(klass="yearMonthContainer") ...code that will depend on user interactions... Note that I use airium rather than direct html + dtl to handle model dependent display (as I find it easier to handle all the data logic but this does not change much for my question. And for the javascript I have found this below, but I cannot find an easy way to call a django view from my script, the only think whih I … -
Django, Nginx, Gunicorn: 400 Bad Request when trying to access the AWS EC2 instance externally
I am encountering a "400 Bad Request" error when attempting to access my Django application externally on an AWS EC2 instance. Notably, the application functions correctly when accessed locally on the server. This issue arises when using Nginx as a reverse proxy and Gunicorn as the application server. For example when I'm on the ec2 instance and uses the command "curl --unix-socket /run/gunicorn.sock localhost/events/" I get the right data from the database. In the chrome console I can see this error: "The Cross-Origin-Openor-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can alos use the localhost origin instead." I have looked at the nginx logs and I don't get any information from that. I have tried many different solutions and looked and followed various tutorials and documentations, but it still won't work. I will add here some of the files that might be needed in figuring out this problem, and ask if you need more information, or can give me any direction of what I could try. tutorials I have looked at: https://www.youtube.com/watch?v=7O1H9kr1CsA https://medium.com/@madhankm/set-up-django-with-nginx-and-gunicorn-on-ubuntu-20-04-lts-8a02748435fe, settings.py (The important parts) … -
Django Docker Nginx can't load static files
I have a django project. I want to deploy it on AWS using Docker. Here is my services in docker-compose-prod.yml: ... api: image: meduzzen-backend-api container_name: django entrypoint: ./start_prod.sh tty: true stdin_open: true volumes: - .:/code - ./code:/apps - static:/code/static expose: - "8000" ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis ... nginx: image: meduzzen-backend-nginx container_name: nginx volumes: - static:/static - ./nginx-conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: static: ... meduzzen-backend-api image was built from Dockerfile: FROM python:3.11.3-alpine ENV PYTHONBUFFERED=1 # Enable pytest-django ENV DJANGO_SETTINGS_MODULE=meduzzen_backend.settings WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt --upgrade pip COPY . . # Copy start.sh script into project folder COPY start.sh . # Give access rights to start.sh RUN chmod +x start.sh RUN chmod +x start_prod.sh EXPOSE 8000 meduzzen-backend-nginx was built from Dockerfile: FROM nginx:1.25.3-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf: upstream django { server api:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /static/; add_header Access-Control-Allow-Origin *; } } start_prod.sh: #!/bin/sh python manage.py migrate python manage.py collectstatic --noinput gunicorn meduzzen_backend.wsgi:application --bind 0.0.0.0:8000 Pages are loaded but it can't load static … -
Django parameterized tests - Problems
I want to test my Django app. To avoid code clones, i want to usere paramerezided testes. I also want to use variables i initialized in the setUp(), to avoid hardcoding e.g. primary keys. But i did not find a fitting solution. Idea 1: Loop from django.test import TestCase from app.models import Example class TestClass(TestCase): @classmethod def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") def test_example(self): for testcase in testcases: self.assertEqual(param.att,"expected) Problem: Cant find failed tests without adding extra debug messages. Idea 2: parameterized library from django.test import TestCase from app.models import Example from parameterized import parameterized class TestClass(TestCase): param1 = None param2 = None def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") @parameterized.expand([ (param1,"foo"), (param2,"bar"), ]) def test_example(self,param, expected): self.assertEqual(param.att,"expected) Problem: param is still None in the test Idea 3: getattr from django.test import TestCase from app.models import Example from parameterized import parameterized class TestClass(TestCase): param1 = None param2 = None def setUp(self): self.param1 = Example.object.create(att="foo") self.param2 = Example.object.create(att="bar") @parameterized.expand([ ("param1","foo"), ("param2","bar"), ]) def test_example(self,param, expected): param = getattr(self, param) expected = getattr(self, expected) self.assertEqual(param.att,"expected) Problem: very slow -
Hreflang conflicts and missing self-referencing hreflang issue in Django-based site
Issue 1: No self-referencing hreflang Description: Issue Type: No self-referencing hreflang. Page URLs: Page URL 1 Page URL 2 Current Hreflang Values: <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/" rel="canonical"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="en" rel="alternate"/> Desired Outcome: Include a self-referencing hreflang tag for the current language. Assumptions: The absence of a self-referencing hreflang tag might be due to the link href containing parameters. Issue 2: Conflicting hreflang and rel=canonical Description: Issue Type: Conflicting hreflang and rel=canonical. Page URLs: Page URL 1 Page URL 2 Current Hreflang Values: <link href="http://localhost:1300/en/blog/1072/" rel="canonical"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/blog/1072/" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="en" rel="alternate"/> Desired Outcome: Ensure consistency between hreflang and rel=canonical URLs. Assumptions: Conflicting hreflang and rel=canonical issue might be due to the same URL marked as canonical and alternate. Additional Context: Code Snippets: base.html: {% with canonical_url=request.build_absolute_uri %} <link rel="canonical" href="{% canonical_url request %}" /> {% endwith %} {% for alt in ALTERNATES %} <link rel="alternate" href="{{ alt.href }}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" hreflang="{{ alt.hreflang }}" /> {% endfor %} context_processor.html: def i18n_alternates(request): """ Generate hreflang alternate URLs for … -
How implement channels with different chats
enter image description here I have a Django project in which I need to implement a chat, as in the photo. I tried using django channels, but I was able to implement one specific chat. How to properly implement a chat of this format. Maybe socketio or something like that would be more optimal. Thanks -
Django Rest Framework for blog site
I want to create a simple blog site using django where i also want to shere my product to show only. Is it needed to install Django Rest Framework here? Can i see my website on mobile without rest framework? I am expecting your help here. -
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "postgres" does not exist This error is I can not slove. please give me a hint. I can not try anything because the issue has a lot. But, I try every thing Ican not solve -
Cannot resolve keyword 'average_rating' into field
Here is my models and views file. class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) @property def average_rating(self): return self.articlecomments.all().aggregate(Avg('rate')).get('rate__avg', 0.00) class ArticleComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True, blank=True, related_name='articleratings') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='articleratings_author') rate = models.IntegerField(default='0') class ArticleByCategoryViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-average_rating') serializer_class = ArticleSerializer pagination_class = StandardResultsSetPagination What I try to do is sort the articles by its rating but it does not work. It gives me this error: raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'average_rating' into field. Choices are:...... I used it as a property.How can I solve this problem?Is there an alternative way? -
CORS Errors while accessing the REST API in REACT
I have installed the django-cors-headers and configured the following in my settings.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'atpdocuments', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # or specific domains # other allowed origins... ] After adding this also im not able make a request from React. Getting the following error Access to fetch at 'http://127.0.0.1:8000/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. I have tried the above methods but still iam getting the cors errors. -
How to order a Django queryset by two separate columns
I have a ‘Entry’ model with two columns, ‘wins’ and ‘points’. Right now I am ordering them by wins but when there are two people with the same amount of wins I would like to fall back on points as a tie breaker. Is there a way to order by 2 separate data points? -
Video Title space giving Directory not found error
I am working on a downloader but while downloading a video (eg. Staying Alive) The space between Staying and Alive is giving directory error I tried to fix using methods given by chatgpt but it doesnt work for my case def download_video(video_url, download_path, resolution='720p'): video = YouTube(video_url) stream = video.streams.filter(res=resolution, file_extension='mp4').first() if stream: print(f"Downloading: {video.title}") file_path = os.path.join(download_path, f"{slugify(video.title)}.mp4") stream.download(download_path) return file_path else: print(f"Error downloading: {video.title}") return None def create_zip(zip_filename, files_to_zip): with zipfile.ZipFile(zip_filename, 'w') as zip_file: for file_path in files_to_zip: #each file to the zip file print(file_path) file_name = os.path.basename(file_path) zip_file.write(file_path, file_name) def download_files(request, downloaded_files): base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = '/test.zip' filepath = base_dir + '/media' + filename create_zip(filepath, downloaded_files) thefile = filepath filepath = os.path.basename(thefile) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(thefile, 'rb'), chunk_size), content_type=mimetypes.guess_type(thefile)[0]) response['Content-Length'] = os.path.getsize(thefile) response['Content-Disposition'] = "Attachment;filename=%s" % filename return response How exactly I have to do the fix? -
annotate() + distinct(fields) is not implemented. Python Django Error
When I try to use annotate with distict following error occurs NotImplementedError at /guest/book/1/checkavailability/ annotate() + distinct(fields) is not implemented. Request Method: GET Request URL: http://localhost:8000/guest/book/1/checkavailability/?start_date=2023-11-19&end_date=2023-11-28 Django Version: 4.2.7 Exception Type: NotImplementedError Exception Value: annotate() + distinct(fields) is not implemented. Exception Location: /home/abk/Desktop/project-qb/django/lib/python3.11/site-packages/django/db/models/sql/compiler.py, line 872, in as_sql Raised during: booking.views.views.RoomsAvailableBetweenSpecificDatesView Python Executable: /home/abk/Desktop/project-qb/django/bin/python Python Version: 3.11.4 Here is my query booked_rooms = RoomBooking.objects.filter( (Q(booking__start_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__end_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__start_date__lt=lookup_start_date, booking__end_date__gt=lookup_end_date)), booking__hotel=self.hotel, booking__guest_status__in=[ settings.NOT_CHECKED, settings.CHECKED_IN], ).select_related('booking', 'room').exclude(room__is_deleted=True).distinct('room__room_number').values(room_type=F('room__room_type')).annotate(count=Count('room__room_type')).order_by('room__room_type') Here is my model class RoomBooking(models.Model): booking = models.ForeignKey("Booking", on_delete=models.CASCADE) room = models.ForeignKey("Room", on_delete=models.CASCADE) class Room(models.Model): room_number = models.CharField(max_length=25) hotel = models.ForeignKey("Hotel", on_delete=models.CASCADE) room_type = models.CharField(max_length=25) rate = models.IntegerField(validators=[MinValueValidator(0)]) is_deleted = models.BooleanField(default=False) class Booking(models.Model): NOT_CHECKED = 'not checked' CHECKED_IN = 'checked in' CHECKED_OUT = 'checkout out' CANCELLED = 'cancelled' GUEST_STATUS = [ (NOT_CHECKED, "NOT_CHECKED"), (CHECKED_IN, "CHECKED_IN"), (CHECKED_OUT, 'CHECKED_OUT'), (CANCELLED, "CANCELLED") ] hotel = models.ForeignKey('Hotel', on_delete=models.CASCADE) guest = models.ForeignKey( "authentication.User", on_delete=models.CASCADE, null=True) total_rooms = models.IntegerField( default=1, validators=[MinValueValidator(1)]) start_date = models.DateTimeField() end_date = models.DateTimeField() booked_date = models.DateTimeField(auto_now_add=True) guest_status = models.CharField( max_length=15, choices=GUEST_STATUS, default=NOT_CHECKED) How could I make the same query without the issue ? After some googling I've found that if we try to call distinct on an annotated query, it sometimes works, sometimes get's …