Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin stackedinline adding new data
I am using stackedInline for Django admin and when trying to add new data the existing data appears below as new tabs how can I solve that. my model category is as follows class Category(models.Model): '''category model for the genere of the stories''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='categories', on_delete=models.CASCADE, null=True, blank=True ) is_primary = models.BooleanField(default=False) parent_category = models.ForeignKey( "self", related_name="children", on_delete=models.SET_NULL, null=True, blank=True, default=None) and my admin is like this class TabedAdmin(admin.StackedInline): model = Category extra = 1 class CategoryAdmin(admin.ModelAdmin): inlines = [TabedAdmin, ] def get_queryset(self, request): queryset = super(CategoryAdmin, self).get_queryset(request) queryset = queryset.filter(is_primary=True).all() # you logic here to `annotate`the queryset with income return queryset and when trying to add new data from the admin the form shows that the first section is empty and all the available categories are listed as like an edit view from the second tab itself. what might be the reason for this? -
Settings.py returning ModuleNotFound error on app that exists
I am relatively new to Django and trying to create a simple app to enable a user to signup and login However when I try to runserver to test what I currently have I run into this error message: ModuleNotFoundError: No module named 'signup.app' This is the structure of my project peerprogrammingplat --- peerprogrammingplat --- signup this is my installed apps in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'signup.app.SignupConfig', ] my views.py from .models import * def register(response): form = UserCreationForm() return render(response, "signup/register.html", {"form":form}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', signupv.register, name="register"), ] -
[Django]Intermittent unauthorized API requests when using tokens
I am using tokens for Django rest API authentication. I noticed that in the logs, from time to time, there are unauthorized requests. The user that the token created for is set to be superuser, and other requests are successful, so it shouldn't be the problem of the token/permission. Is there some kind of connection pool limit or anything that would cause such unauthorized problem but then recover quickly? I am using 'rest_framework' and 'rest_framework.authtoken'. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } -
React/Django cannot update data in a table without also updating the image field associated with it
I am developing a web application project for an alumni group using react/django and using axios to fetch data. Right now, I am able to Create an event with fields such as (event_name, date, images, etc.). I am also able to update the event details, but my problem is that I cannot update any other fields without also changing the picture. I've handled the null requests through django and when I test on Postman and any api views, POST/PUT/DELETE/GET all work fine, so I believe it's something to be handled in react. The image field is labeled gallery. Below is a js file that contains a form that populates the form inputs with the data from for a particular event. Any help would be appreciated. I've tried to look for other answers, but just because they might be out there, doesnt mean I know where to look or how to interperet that is what I'm doing wrong, seeing im just a beginner. import React, { useState, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { getEventById, updateEventById } from "../../../api/apiCalls"; const EventUpdate = () => { let navigate = useNavigate(); const { id } = useParams(); … -
Multiple related foreignkeys
class Flow(models.Model): name = models.CharField(max_length=200) pre_requisite = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) pre_requisite_status = models.ForeignKey("FlowStepStatus", on_delete=models.SET_NULL, null=True, blank=True, related_name='pre_requisite_status') This gives me one pre-requisite and it's status (pre_requisite_status). But I want to have flexibility for multiple pre_requisite and their respective statuses. How can I modify model to have it? -
Make a route expire in a short time
I am trying to implement a task that for rating services. Users will be receiving a SMS text message including a short link. After click that short link, they will fill out the information and submit. And then I will store those information in the database. That is the requirement, now move on to implement part. I am thinking to generate a route like this: https://www.app.com/{customerId}/?access_token=fdsaf.dsaf.fdsafads Then put it under bitly or short.io. The access_token will only valid for 10 seconds start from the time that the url is generated. Do you think is it good enough for safety ? any suggestion would be highly appreciate. Thank you. -
messages.error doesn't work with fetch js in form, Django
views: if request.method == "POST": user_name = request.POST['user_name'] email = request.POST['email'] password = request.POST['password'] re_password = request.POST['re_password'] if len(user_name) >= 16: messages.error(request, 'Too long') ... js: const form = document.forms["register_form"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; form_data = new FormData(form); myHeaders = new Headers() myHeaders.append("X-CSRF-Token", csrftoken) fetch("/account/register/", { headers: myHeaders, body: form_data, method: "POST" }).then(function (response) { if (response.ok) { console.log("successfully registered"); return response.json(); } return Promise.reject(response); }).then(function (data) { console.log(data); }).catch(function (error) { console.warn('Custom Error:', error); }); }) html: <form method="POST" name="register_form" id="register-form"> {% csrf_token %} .... fields .... {% for message in messages %} {{message}} {% endfor %} form working correctly and POST data without reloading page... but problem is about messages.error it doesn't work in template...any problem ? there is any solution to show errors from views in back-end without page refresh ? -
GCC ERROR IN CPanel Terminal Trying to Install Pillow
Please I need help, I am trying to host a Django Project in Cpanel. I have created a Python App (Python 3.8.6) Launched the Virtualenv on Terminal and install django according to my project version (Django 3.2.6) Now Trying to install Dependencies such as Pillow and Mysqlclient, I keep getting the below error. unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory building 'PIL._imagingmorph' extension /opt/rh/devtoolset-7/root/usr/bin/gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -I/usr/include/freetype2 -I/tmp/pip-build-hrzlinrf/pillow -I/home/westhfef/virtualenv/humanities/3.8/include -I/usr/include -I/opt/alt/python38/include/python3.8 -c src/_imagingmorph.c -o build/temp.linux-x86_64-3.8/src/_imagingmorph.o unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory error: command '/opt/rh/devtoolset-7/root/usr/bin/gcc' failed with exit status 1 I have tried everything I can, but didn't work. -
How to reference queryset result in Django
The class model I wrote is complex and large, so I can't write all the code here. Please understand. [views.py] separate_line = Assignment.objects\ .values('id')\ .annotate(ABC=Min(F('feedback__ABC_date')))\ .annotate(C1D1_ABC=ExpressionWrapper(Cast(F('feedback__injection_date'), DateField()), output_field=DateField()) - ExpressionWrapper(Cast(F('ABC'), DateField()), output_field=DateField())) \ .values('id', 'C1D1_ABC') Result: <QuerySet [{'id': 3391, 'C1D1_ABC': datetime.timedelta(days=13)}, {'id': 3392, 'C1D1_ABC': datetime.timedelta(days=27)}]> I succeeded in extracting the desired queryset by creating the C1D1_ABC field using id and annotation. ABC_C1D1 = Feedback.objects.values('assignment__research')\ .annotate(separate_sum=Sum(separate_line['C1D1_ABC'], filter=Q(assignment_id__in=separate_line['id'])), separate_count=Count('assignment', distinct=True, filter=Q(assignment_id__in=separate_line['id'])))\ .values('assignment__research__research_name', 'separate_sum', 'separate_count')\ I am trying to apply the queryset result(-> separate_line) to another ORM calculation, but the following error occurs. Error Message: QuerySet indices must be integers or slices, not str. If I replace ['id'] with [0] referring to the error message, the following error message occurs. Error Message: Field 'id' expected a number but got 'id'. -
Attribute Error while importing views in Urls.py in django rest framework
views.py from rest_framework.decorators import api_view from rest_framework import status from django.shortcuts import render from rest_framework.views import APIView from rest_framework import authentication, permissions from django.contrib.auth.models import User from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response from App.serializers import * from App.models import * from App.serializers import * # Create your views here. class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) @api_view(['GET']) def consol_overall_view(request): user = Users.objects.values('id','employee_name','billable_and_non_billable',) qs = conso_serializers(user, many= True) proj = Add_Job.objects.values('project','user','client') qs1 = timelog_serializers(proj, many= True) cli = Add_Timelog.objects.values('Date','Hours','project_id') qs2 = time_serializers(cli,many= True) return Response(qs.data+qs1.data+qs2.data,status = status.HTTP_200_OK) urls.py from django.contrib import admin from django.urls import path,include from django.urls import re_path from django import views from App.views import CustomAuthToken from.router import router from rest_framework.authtoken import views from django.views.generic import TemplateView from … -
Is there a way to Connect your Google Reviews into a Django Website?
been looking for a tutorial whereby one can connect automatically the reviews they receive from Google My Business and add them as testimonials to a Django Website. -
Images are not getting displayed on my website (HTML)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>AYNTK</title> </head> <body> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="templates\Slide 1.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 2.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 3.jpg" class="d-block w-100"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html> I am really new to designing with HTML and CSS... I took this code from Bootstrap website, trying to create a carousel and added the relative path of my images to the img tag as source. The images does not get displayed on the website.. What can possibly be the reason? -
Basic idea to access items in S3 bucket from Browser
I use [django-s3direct][1] to upload file to S3 bucket. Once file is uploaded there comes url appeares here. https://s3.ap-northeast-1.amazonaws.com/cdk-sample-bk/line-assets/images/e236fc508939466a96df6b6066f418ec/1040 However when accessing from browser, the error comes. <Error> <script/> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>025WQBJQ5K2W5Z5W</RequestId> <HostId>FF3VeIft8zSQ7mRK1a5e4l8jolxHBB40TEh6cPhW0qQtDqT7k3ptgCQt3/nusiehDIXkgvxXkcc=</HostId> </Error> Now I can use s3.ap-northeast-1.amazonaws.com url? or do I need to create access point ? Access permission is public and bloc public access is off Bucket policy is like this { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::678100228133:role/st-dev-base-stack-CustomS3AutoDeleteObjectsCustomR-MLBJDQF3OWFJ" }, "Action": [ "s3:GetBucket*", "s3:List*", "s3:DeleteObject*" ], "Resource": [ "arn:aws:s3:::cdk-st-dev-sample-bk", "arn:aws:s3:::cdk-st-dev-sample-bk/*" ] } ] } Is there any other things I need to check? -
Dynamic Django urls redirects to the wrong function
So what I am trying to do is create urls such that the user can see complaints either by passing a particular parameter or sort by upvotes by default if no parameter is passed. urls.py path('', views.exploreComplaints, name='explore-complaints'), path('?sort_by=<str:sorting_parameter>/', views.exploreComplaints, name='explore-complaints-by-parameter'), views.py def exploreComplaints(request, sorting_parameter="upvotes"): complaints = Complaint.objects.all() if(sorting_parameter=="name"): complaints = sorted(complaints, key = lambda x : x.complaint_name) else: complaints = sorted(complaints, key = lambda x : x.complaint_upvotes, reverse = True) context = {'complaints':complaints} return render(request, 'complaints/complaints.html', context) The sorting parameter does not work when I go to a URL, the value of sorting_parameter is always upvotes, even when I go to a url with ?/sort_by=name in the end. Where am I wrong? -
Rest django checking the duplicate number
if i adding the number 5 i want to check all the numbers before 5( like 1,2,3 and 4 )is must have inside the db ,then only can i add the number 5 ,otherwise show error. And also check is any duplication in the Db using rest django model serilaizer. -
Download Html file instead of render in Django
So I am pretty much a django newbie, I do not even know if what I am asking is possible ;-; So basically what I'm making is a website where users can pass context Then django populates a template with the context But instead of rendering the template I want to make the template populated with context available for download I want to be able to download index.html I know browsers have a save webpage feature but on mobile the javascript does not work and the icons i got from Google icons also do not load -
Need help accessing session variables in Django Channels consumers.py
I am generating a random userid and storing it as a session variable in my view. I am trying to access that session variable in consumers.py to identify the user (not authenticated ) and update the user about the changes in the database. view.py : def index(request): request.session['uniqueid'] = 'random_number' print(request.session['uniqueid']) # this is working return render( request, 'home.html', ) consumers.py: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() U = self.scope['session']["uniqueid"] Error: Exception has occurred: KeyError (note: full exception trace is shown but execution is paused at: connect) 'uniqueid' I changed localhost to 127.0.0.1 ('ws://127.0.0.1:8000/ws/socket/') as described in https://stackoverflow.com/a/67242832, but receive the same error. I am unable to pin down the error, any help would be appreciated. -
Initialize a container model with child models when a new container is created - e.g. Todo list with default tasks
I'm trying to create a todo list as part of an application that is used to prompt a user what they must complete before the application is assessed. To achieve this I have created a TaskList model and a Task model belonging to a TaskList. When I create a new TaskList instance (on a new application) I want to prepopulate the list with some default Tasks that will always be present on every new application. I'm relatively new to Django and Python, so I'm just looking for a push in the right direction. Is there some kind of Django model initialize function I can override on the TaskList to create these default tasks? -
How can I use a Django model's verbose_name in a field definition?
I have the following model: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... exists = models.BooleanField( verbose_name = 'The Foo still exists.', default = True ) ... What I would like to do is use the model's verbose_name in place of 'Foo', so that my model would look something like this: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... exists = models.BooleanField( verbose_name = f'The {self._meta.verbose_name} still exists.', default = True ) ... Obviously, this doesn't work as written since self doesn't exist in that context. I tried the following, which seemed to work: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... def __init__(self,*args,**kwargs): super().init(*args,**kwargs) self.exists = models.BooleanField( verbose_name = f'The {self._meta.verbose_name} still exists.', default = True ) ... However, when I tried Foo.save() I ended up with django.core.exceptions.FieldError: Invalid field name(s) for model Foo: 'exists'. Ultimately, I intend to make Foo into an abstract model for other models to inherit (which is not the question here, just some added context). The question is, how can I use the model's verbose_name in the field definition? -
Django exclude from queryset if all attributes of the set not match
I have 2 models Course and Class I'm trying to exclude the courses where ALL his classes vacancies are 0, but this query is excluding the course if only one of the class vacancies is 0. courses = Course.objects.all().exclude(class_set__vacancies=0) Classes: -
Django: select values from related table
I have these two simple tables: # Table manufacturers in my db: # | id | name | # |----|-------| # | 1 | Tesla | # | 2 | BMW | # Table cars in my db: # | id | model | make | # |----|---------|-------| # | 1 | Model 3 | Tesla | # | 2 | M5 | BMW | # | 3 | Model S | Tesla | So here are my models.py: from django.db import models class ManufacturerModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, unique=True) class Meta: managed = False db_table = 'manufacturers' class CarModel(models.Model): id = models.IntegerField(primary_key=True) model = models.CharField(max_length=255) make = models.ForeignKey( ManufacturerModel, on_delete=models.DO_NOTHING, null=False, to_field='name', db_column='make' ) class Meta: managed = False db_table = 'cars' I need to get this object: manufacturers = { 'Tesla': ['Model 3', 'Model S'], 'BMW': ['M5'] } Or at least this one: manufacturers_1 = [ { 'id': 1, 'name': 'Tesla', 'cars': [ { 'id': 1, 'model': 'Model 3', 'make': 'Tesla' }, { 'id': 3, 'model': 'Model S', 'make': 'Tesla' } ] }, { 'id': 2, 'name': 'BMW', 'cars': [ { 'id': 2, 'model': 'M5', 'make': 'BMW' } ] } ] Basically it's just a very … -
How to trigger signals for User model whenever profile is updated in django?
I am using signals to create a profile whenever a user account is created. This works fine. It also updates the profile whenever the user's username is changed. The problem here is that I wanted to edit the user's first_name and last_name only when the profile is edited so I tried using signals in which the receiver is now the CustomUser model. But, I don't think I am doing it right. # accounts/models.py class CustomUser(AbstractUser): age = models.IntegerField(null=True, blank=True) bio = models.TextField(null=True, blank=True) class Meta: unique_together = [['first_name', 'last_name']] # pages/models.py class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) # accounts/signals.py @receiver(post_save, sender=Profile) def update_profile(sender, instance, created, **kwargs): if not created: print("Custom user updated!") # pages/signals.py @receiver(post_save, sender=CustomUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print("Profile created!") @receiver(post_save, sender=CustomUser) def update_profile(sender, instance, created, **kwargs): if not created: instance.profile.save() print("Profile updated!") -
How can I get 'sign in with Google' to work using 'dj_rest_auth'?
I'm trying to implement Google sign in using DRF and dj_rest_auth. I've set up 'django-allauth' with Google as provider and the sign in process works in the web browser. I need to connect an android app with my backend. I've created API endpoints which will require authentication. According to the docs, code is required in order to complete authentication and receive the token. After doing some research, I found that code required by dj_rest_auth can be obtained by visiting: https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<YOUR CALLBACK URL>&prompt=consent&response_type=code&client_id=<YOUR CLIENT ID>&scope=openid%20email&access_type=offline However, even after passing code returned in the query param (after decoding from URL format), the following error is shown: Error retrieving access token: b'{\n "error": "invalid_grant",\n "error_description": "Bad Request"\n}' To see if I can log in with a recent access token, I signed in with my Google account from the homepage , copied the access token from the admin section and submitted it to the endpoint http://localhost:8000/dj-rest-auth/google/. I was able to receive the auth token generated by dj_rest_auth. I need help in getting the auth token by providing code in the post request. My code: # urls.py ... path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/google/', home.GoogleLogin.as_view(), name='google_login'), ... # views.py from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import … -
the best way to keep the font-size the same on all devices
I am struggling with setting up the font-size so it looks similar in all desktop devices. For now the problem is that on my new laptop sidebar ends on 75% of total web height and on my old laptop it is exceeding 100% of screen height and I had to implement scrollbar. Is there anything I can do to prevent from it and to keep it the same. I tried these 2 solutions but they don't work]. I am using default Bootstrap 5 typography. I am using h1-h6 and p tags on all websites. No custom font sizes and classes applied. -
Where should I put extra logic in django project?
I want to check time continuously (maybe using multi threading) and if it is 12 midnight I want to update database. Where should I put these kind of logic in django project. Is it okay to put these king of code in manage.py?