Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Drill down page in Django
I'm doing my student project in Django. Now I have interesting task: drill-down page for user. He/she logs in and sees drop-list of the companies he/she has the right to view. When user chooses one of the company under that list appears another one - list of the vehicles owned by that companies. When user selects the vehicle, another list appears - list of the routes this car made so far. When user selects the car, another list appears - list of the route points, with the names of the points instead of coordinates. I tries to find out some libs or frameworks. I found out django-rest-framework-drilldown but it's fairly old enough for not to work. )) I'm kind of good with backends and apps with no graph but doing something on the front-end side almost gives me panic attack. -
Pictures can’t open. Why do this happen?
Why is this happening? While I am making a simple website, pictures can’t open -
Django: How to customize an add view of a model into another
I have just approached Python and Django. I am practicing with Django 4.1.7. Scenario: I have a model called Company with its name at one of its attributes. I design another model called "Company Detail" to store company information such as addresses, and phones. They are connected with the foreign key of course. Now, I write a function to create a view on the admin page for adding a new Company with its name. And I want to add the "Company Detail" on the same page. Go to the point I found a way to do that using TabularInline. However, the Company Detail's fields are many and it broke my layout. The 'country' field bleeds out of the main screen on the right, and so on with others. That's why now I want to make it display vertically. Is there any way in Django that I may archive this? -
React JS npm run build does not create index.html file correctly
Following this video guide: https://www.youtube.com/watch?v=W9BjUoot2Eo&ab_channel=DennisIvy ; however when I run npm run build after I get no compiled javascript in my index.html file; when running the server it is just a blank webpage. However when doing npm start and running the server prior to this I don't get these issues and it works fine. Note I do not receive any error messages, and also get a 404 issue. I ran npm start build, I expected something like: <!doctype html>React AppYou need to enable JavaScript to run this app.!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([]) But I get: <!doctype html>React AppYou need to enable JavaScript to run this app. -
Django filters ordering fix nulls position
This class is needed to override standard PostgreSQL behavior and move NULL values to the end of the list for DESC sorting and to the beginning of the list for ASC api/filters.py from django.db.models import F from django_filters import OrderingFilter class ImprovedOrderingFilter(OrderingFilter): """ This class is needed to override standard PostgreSQL behavior and move NULL values to the end of the list for DESC sorting and to the beginning of the list for ASC """ def get_ordering_value(self, param): descending = param.startswith('-') param = param[1:] if descending else param field_name = self.param_map.get(param, param) ref = F(field_name) return ref.desc(nulls_last=True) if descending else ref.asc(nulls_first=True) myapp/filters.py class UserFilterSet(FilterSet): ordering = ImprovedOrderingFilter( fields=( ... ) ) -
Django Create Single Queryset That Counts Objects of Two Models By Month
I have two models that I'm trying to get the object counts of each by month class Car(models.Model): car_user = models.ForeignKey(User, on_delete=models.CASCADE) car_title = models.CharField(max_length=200) car_purchase_date = models.DateTimeField() class Truck(models.Model): truck_user = models.ForeignKey(User, on_delete=models.CASCADE) truck_title = models.CharField(max_length=200) truck_purchase_date = models.DateTimeField() Was able to get a count by User with this below, but can't figure out how to do the same thing but instead of by user doing by month. Won't bother wasting time and space with the dumb things I've tried so far. Really appreciate any help. count_by_user_chart = User.objects.values('username') \ .annotate(car_count=Count('car__id', distinct=True)) \ .annotate(truck_count=Count('truck__id', distinct=True)) \ End goal would be to be able to produce something like this - +---------------+-----------+-------------+ | Month | Car Count | Truck Count | +---------------+-----------+-------------+ | January 2023 | 3 | 1 | | February 2023 | 4 | 0 | | March 2023 | 0 | 2 | | April 2023 | 2 | 2 | +---------------+-----------+-------------+ -
Django user_logged_in signal not fired when used with django-allauth "remember me"
I am using django-allauth framework to authenticate user logins. I have set up a signal that is fired every time the user logs in. I am also using the "remember me" option for user logins, so that the system remembers the user and does not ask for a username and password on subsequent logins after successful authentication. What I am finding is that the signal fires when the user logs in with a username and password. However, when the user returns to the site and the login is authenticated with "Remember Me", i.e. she does not have to enter username and password; the signal is not fired. I have tried this with both django.contrib.auth.signals.user_logged_in and allauth.account.signals.user_logged_in and the result is the same. I am wondering how I can capture the user login when the user logs in with "Remember Me"? -
Django file upload clears on form submit
when I try to upload a file via FileField with a form, it clears on submit. Here is the form code: class UploadForm(forms.Form): name_of_file = forms.CharField(required=True) color = forms.CharField(required=True) quantity = forms.IntegerField(required=True) file = forms.FileField(required=True) class Meta: fields = ('name_of_file', 'color', 'quantity', 'file') And here is the code for the submit. def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): user = User.objects.get(username=request.user.username, email=request.user.email, first_name=request.user.first_name, last_name=request.user.last, password=request.user.password) if not os.path.exists('stls'): os.mkdir('stls') with open('stls/'+str(time.ctime(time.time()))+'.stl', 'wb+') as destination: for chunk in request.FILES['file'].chunks(): destination.write(chunk) item = Item(name=form.cleaned_data['name'], price=-1,color=form.cleaned_data['color']) order = Order(user=user, item=item, quantity=form.cleaned_data['quantity'], progess=OrderProgress.objects.get(Status="TBD", PercentDone=0)) order.save() return HttpResponse('File uploaded successfully') I have not tried much because I cannot figure out what is happening -
Django User' object is not iterable or not serializable
I am new in Django I have this function in views.py member = list(User.objects.get(id=id)) return JsonResponse(member, safe=False)``` Of course this doesn't work and i have the error: object User is not iterable But if i use `def edituser(request, id): member = User.objects.get(id=id) return JsonResponse(member, safe=False)` i have the error: Object of type User is not JSON serializable How can i solve ? -
'method' object is not subscriptable error appears when using get function
Django rises an error of ('method' object is not subscriptable) when trying to access username attribute from class User . imports : from django.shortcuts import render from .models import Post from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import get_object_or_404 the function that cause the error : class UserPostListView(PostListView): model = Post fields = ['title', 'content'] context_object_name = 'posts' paginate_by = 2 def get_queryset(self): user = get_object_or_404(User, username= self.kwargs.get('username')) return Post.objects.filter(author=user).order_by['-date'] I tried using square brackets instead of parentheses, but it raised a similar error . -
I have tried to update the value of the sale field through the admin panel, but it is not saving
class Category(models.Model): name = models.CharField(max_length=50) category_image = models.ImageField(upload_to='categoryImgs', null=True, blank=True) category_cover = models.ImageField(upload_to='categoryImgs', null=True, blank=True) sale = models.CharField(max_length=2, null=True, blank=True) category_description = models.TextField(max_length=200, null=True, blank=True) category_slug = models.SlugField(("slug"), null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.category_slug: self.category_slug = slugify(self.name) super(Category, self).save(*args, **kwargs) I want to be able to update the data for the sale field and the image -
How can you get DurationField value in seconds in Django
I have a model which uses Django's DurationField to take inputs from users how long a task might take class Step(models.Model): stepnumber = models.CharField(max_length=500) description = models.TextField() duration = models.DurationField(default=timedelta) when I get query for the duration values, it returns values in HH:MM:SS. >>> steps = Step.objects.all() >>> for s in steps: ... print(s.duration) ... 0:00:00 0:01:00 0:02:00 0:05:00 0:04:00 0:00:05 0:01:00 >>> I want to get these values in seconds. Like instead of 0:01:00, I want to get 60. How can I do that. When I check MySQL database, I see that stores the values in microseconds, but shell query returns in HH:MM:SS format. -- Beginner in Django -
aise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'app.user' cannot be resolved
I am running into an issue that's bizarre, I have tried to fix it but have failed, the error you there is caused by whenever I import and user this from django.contrib.auth import get_user_model commands like python manage.py migrate, python manage.py check, python manage.py runserver all run well and show no error, but when i tried to run this test, or any other test that summons "get_user_model" error will come from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): """ Tests models. """ def test_create_user_with_email_successful(self): """ Test creating a user with email is successful. """ email = "test@example.com" telephone = "1234567890" username = "testuser" first_name = "test" last_name = "user" password = "testpass123" user = get_user_model().objects.create_user( email=email, telephone =telephone, username = username, first_name = first_name, last_name = last_name, password=password, ) self.assertEqual(user.email, email) self.assertEqual(user.telephone, telephone) self.assertEqual(user.username, username) self.assertEqual(user.first_name, first_name) self.assertEqual(user.last_name, last_name) self.assertTrue(user.check_password(password)) that test will cause problem since it calls "get_user_model" take look at my user model here from django.db import models from django.contrib.auth.models import( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.conf import settings class UserManager(BaseUserManager): """ minimum fields for all users""" def create_user( self, email, telephone, username, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('You need to provide an … -
Does Django open and close connection to cache every time I call cache.delete(key)?
Consider the following code snippet: from django.core.cache import cache cache.delete('key_1') cache.delete('key_2') If i'm using an Instance of Redis as my default cache, will Django create two seperate connections to the Redis instance, for each call to .delete()? or will it keep a single connection open to fulfil both calls to .delete()? I have a circumstance where I may need to delete a lot of individual keys in one go. Ideally I would like a single connection to the Redis cache to persist, rather than take on the latency of creating a new connection each time a cache method is called. Thanks -
from where did the self.request come from?
Lately I was learning Django and Django rest framework from the official docs and i stumbled upon a method defined inside the GenericAPIView named get_queryset. Till now everything is fine but i was lost when he override this latter the code is as follow: def get_queryset(self): user = self.request.user return user.accounts.all() My question is simple, the request is not defined in the method's argument so where did it come from? -
I am new to django and testing and I'm trying to test a registration and login view
The view has IsAdminUser restriction. I am also using token authentication. This is the tests code: class TestSetUp(APITestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user_manager = UserManager() def setUp(self): self.register_url = reverse("user_urls:register") self.register_user_data = { "name": "TestUser", "email": "test_user@email.com", "number": "1213", "password": "Test@123", } self.login_url = reverse("user_urls:login") self.login_user_data = { "name": "TestUser", "password": "Test@123", } self.register_user_data_with_empty_password = { "name": "TestUser", "email": "test_user@email.com", "number": "1213", "password": "", } return super().setUp() def create_staff(self): self.user = self.user_manager.create_staff(**self.register_user_data) try: self.token = Token.objects.get(user=self.user) except Token.DoesNotExist: self.token = Token.objects.create(user=self.user) def create_superuser(self): self.user = self.user_manager.create_superuser(**self.register_user_data) try: self.token = Token.objects.get(user=self.user) except Token.DoesNotExist: self.token = Token.objects.create(user=self.user) class TestViews(TestSetUp): def test_register_with_no_data(self) -> None: res = self.client.post(self.register_url) self.assertEqual(res.status_code, 401) def test_register_with_data(self) -> None: User.objects.create_staff(**self.register_user_data) res = self.client.post(self.register_url) self.assertEqual(res.status_code, 201) def test_user_cannot_login_with_invalid_credentials(self): self.client.post(self.register_url,self.register_user_data, format='json') res = self.client.post( self.login_url, self.login_user_data, format="json") self.assertEqual(res.status_code, 401) def test_user_can_login_with_valid_credentials(self): res = self.client.post( self.register_url, self.login_user_data, format='json' ) if res.status_code != 201: raise ValueError(f"Registration failed with error: {res.data}") name = res.data["name"] password = res.data["password"] user = User.objects.get(name=name, password=password) user.is_verified = True user.save() response = self.client.post( self.login_url, self.login_user_data, format="json") self.assertEqual(response.status_code, 201) Every time I run coverage I get a 401 Error with the message ValueError: Registration failed with error: {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} I haven't tried much because I … -
Problems with custom footer in catalogue pages in geonode-project
I edited the footer.html template, in my geonode-project in order to set a custom footer, but since that footer has many elements, it does not give enough space for the dataset's result list (and other catalogue pages). The footer seems to be fixed to the bottom. How can I fix that in order to give more space to the resulsts list There is my code I edited the footer.html template in order to set a custom footer, but since that footer has many elements, it does not give enough space for the dataset's result list (and other catalogue pages). The footer seems to be fixed to the bottom. How can I fix that in order to give more space to the resulsts list There is my code <footer> <div style="display: grid; grid-template-columns: 1fr; grid-template-rows: 2fr 1fr; height:20rem; padding: 1%; background: #033E84;"> <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows:1fr;"> <div style="display: flex; justify-content: center; align-items: center;"> <div style="display: flex; flex-direction: column; color: #fff"> <span style="text-align: center; border-bottom: solid 1px; margin: 0 0 6px 0px; font-weight: 600;">Otros enlaces de interés</span> <span><a style="color: #fff;" href="https://consultacf.ineter.gob.ni/">Consulta catastro</a></span> <span><a style="color: #fff;" href="https://tramites.ineter.gob.ni/">Tramites en línea INETER</a></span> <span><a style="color: #fff;" href="https://www.ineter.gob.ni/">INETER</a></span> </div> </div> <div style="display: flex; … -
How to redirect to specific url after logging in, with geonode-project?
In geonode when an user logs in, it is automatically redirected to the Profile page. I am trying to change that and redirect to the Home (index page). In order to to that I added the following line to the settings.py" in my geonode-project folder. But the user is still redirected to the Profile page when he/she performs the authentication ACCOUNT_LOGIN_REDIRECT_URL = "/" I also tried with the following line: LOGIN_REDIRECT_URL = "/" Am I doing something wrong? According to the geonode documentation (https://docs.geonode.org/en/master/basic/settings/index.html) the ACCOUNT_LOGIN_REDIRECT_URL "allows specifying the default redirect URL after a successful login.", so why is not working? -
Django - public class?
My Django project conventionally relied on functions, where many of them would retrieve the same variables/data from the database/request data. Although this works fine, it's inefficient due to the repeared code in every view function. So, I started looking at classes instead, and it seems to be the better solution for creating objects with certain reusable data. To make the data "Public", I'm storing the class object in a Public variable when returning the request data on page load, then calling that variable on subsequent calls. Although this works, it doesn't feel like a best practice. What's the best practice to make the class "Public" so that subsequent Ajax/JS calls/requests can call the same object without recreating it (unless the page changes)? Further, how could I then create multiple instances of the class in case of multiple concurrent pages calling the same view? -
How to get label of checked inupt in css
How can I change the background-color of the label from a checked radio button. Django renders form radio inputs like this: <label for="id_form-level_0"> <input type="radio" name="form-level" value="1" required="" id="id_form-level_0"> description </label> I dont have the intention to change this, so the most commun solution input[type="radio"]:checked + label { background-color: red; } does not work. In addition the :has() selector seems not to be supported in the browsers, meaning the following code neither works. label:has(input[type="radio"]:checked) { background-color: red; } What is the correct way to adress the right label in css? -
Use __str__ children classes methods when calling parent class
I've some classes like these : class Event(models.Model): beginning = models.fields.DateTimeField(null=False, blank=True, default=date.today) end = models.fields.DateTimeField(null=False, blank=True, default=date.today) class Festival(models.Model): name = models.fields.CharField(max_length=100, blank=True) def __str__(self) -> str: return f"{self.name}" class FestivalEdition(Event): type = "festival_edition" father_festival = models.ForeignKey(Festival, default="", on_delete=models.CASCADE, related_name="edition") def __str__(self) -> str: return f"{self.festival_name} {self.year}" As you can see, only the children classes have their __str__ methods. When I use Event (by the admin interface or by shell), the name is like this <Event: Event object (1)>. How can I use the __str__ methods of the children (and children of children) classes when calling the parent class ? I've read the official documentation of Django about inheritance and this post. I tried this : class Event(models.Model): objects2 = InheritanceManager() # The __str__ of Event call the __str__ of children models def __str__(self) -> str: event_name = Event.objects2.filter(pk=self.pk).select_subclasses()[0].__str__() return f"{event_name}" It works well but only with the children but not the children of the children because I get this recursion Error in this case : RecursionError: maximum recursion depth exceeded while calling a Python object. -
Method Not Allowed (POST) in django
I use axious for requests But I get this error POST http://127.0.0.1:8000/dashbaord/Menu/editStatus 405 (Method Not Allowed) What should I do to solve this problem? myscript.js: let changeStatus = (id, place) => { axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios({ method: 'post', url: 'editStatus', data: { 'tes1': 'test', 'tes2': 'test' }, headers: { "content-type": "application/json" } }).then(function (response) { console.log('dsdsdsd') }).catch(function (error) { console.log(error) }); } urls.py path('editStatus', EditMenuItemStatus.as_view(), name="edit_status_item") views.py class EditMenuItemStatus(BaseDetailView): def post(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) -
Datables.net resize column manually resizable colimd
I know this is not a builtin but I have been searching so long for a solution. If anyone knows that would be really great!!! I HAVE TRIED A LOT of solutions but none fit the reorder and other builtins functions... -
WSGI Django Apache, AH01630: client denied by server configuration
I've seen very very similar issues but i don't see how the fixes are relevant to my issue. I have a django server running and working fine, I've setup apache for it to run there with the config file as: Alias /static /home/dev/pidjango/gamificationECM2434/mysite/static <Directory /home/dev/pidjango/gamificationECM2434/mysite/static> Require all granted </Directory> <Directory /home/dev/pidjango/gamificationECM2434/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django python-path=/home/dev/pidjango/gamificationECM2434/mysite python-home=/home/dev/pidjango/djenv WSGIProcessGroup exSeed WSGIScriptAlias / /home/dev/pidjango/gamificationECM2434/mysite/mysite Any help to figure out the issue would be great thank you :) -
Session or Token auth for Backend and two Frontend apps at different locations
I have a Django App which acts backend and some endpoint built with Django REST Framework. There are 2 pieces of frontend interacting with my Django app. I have not implemented auth/login to my app. But before i do that, i have few questions to ask. Below is a picture of the system. Both React_user is a React app BUT React_admin is a low-code app like Retool (drag & drop components to make UI connected via REST API to backend) which is sitting at differnt servers i.e physically seperated at differnt locations React_user is the app for customer where they should be able to login with username and password created by React_admin React_admin is the on who creates customers, create username, password for each customer. Think of this as walk-in account creation as there is no sign-up for customers. So, React_admin creates customer credentials from the React app managed by admin, again is sitting at differnt server. For simplicity, let's say React_admin is hosted at the office itself. To create users, i'm using basic django Users model comes out of the box.So, to create a user, there is a an endpoint made with Django REST Framwork. The endpoint is https://mapp.com/rest/create_user …