Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can we create arrayfield without creating model container?
I am facing problem in creating array field in mongo using django... I am using djongo connector... can't we create ArrayField in without specifying the model container ... I don't want to specify model_container in ArrayField because I don't want to make my model a child class and don't want to give value each and every field for parent class assigned in model_container... I tried - from djongo import models models.ArrayField() I am expecting - I just want to create array field in mongo db with json format/dictionary inside like [{"key1":"value1"}, {"key2":"value2"}] -
How do I make my content published automatically after a Webflow POST request
So I am adding items in my collection that I have in Webflow. The POST request I make is something like this. url = "https://api.webflow.com/collections/<collection_id>/items" payload = {"fields": {}} headers = { "accept": "application/json", "content-type": "application/json", "authorization": <bearer_token> } requests.post(url, json=payload, headers=headers) I added '?live=True' in my URL which apparently means that my content should be published without me needing to do it manually from Webflow. However, it doesn't work. Every time I create an item using a POST, I have to go to Webflow and publish my content. Is there a way around it? -
Django Group by month and display in template by month
`class Daily(models.Model): transid = models.AutoField(primary_key=True) transdate = models.DateField() transdetails = models.ForeignKey(Details, on_delete=models.CASCADE) transcategory = models.ForeignKey(MasterCategory, on_delete=models.CASCADE) transmode = models.ForeignKey(PaymentMode, on_delete=models.CASCADE) transsubdetails = models.CharField(max_length=100, blank=False, null=False) transamount = models.DecimalField(max_digits=7, decimal_places=2) objects = models.Manager() def __str__(self): return "%s %s %s %s %s %s %s" % ( self.transid, self.transdate, self.transdetails, self.transcategory, self.transmode, self.transsubdetails, self.transamount)` Above is my model And my template is as below {% for month in months %} <h3>{{ month__month }}</h3> <table style="width: 100%"> <tr> <th>ID</th> <th>Date</th> <th>Details</th> <th>Category</th> <th>Pay Mode</th> <th>Sub Details</th> <th>Amount</th> </tr> {% for trans in mydata %} <tr> <td>{{ trans.transid }}</td> <td>{{ trans.transdate }}</td> <td>{{ trans.transdetails }}</td> <td>{{ trans.transcategory }}</td> <td>{{ trans.transmode }}</td> <td>{{ trans.transsubdetails }}</td> <td>{{ trans.transamount }}</td> </tr> {% endfor %} </table> {% endfor %} and my view is def alltrans(request): my_data = Daily.objects.all() mnths = len(Daily.objects.values('transdate__month').distinct())+1 totamount = Daily.objects.all().aggregate(totb=Sum('transamount'))['totb'] mnths1 = Daily.objects.values('transdate__month').distinct(), monthsba = [Daily.objects.filter(transdate__month=month) for month in range(1, mnths)] ms = { 'months': mnths1, 'monthsbal': monthsba, 'mydata': my_data, 'totamount': totamount, 'title': 'All Trans', } return render(request, 'alltrans.html', ms) I am trying to bring in template by month ... January sum(transamount) filter by month = 1 id Date Details Category Pay Mode Sub Details Amount February sum(transamount) filter by month = 2 and so … -
How to Django handle multiple requests send at the same time
In a web application, multiple requests can be sent to the server at the same time. Handling these requests can become a challenging task, especially if the server has to perform complex operations, like making API requests, performing database queries, etc. In this post, we will discuss how Django can handle multiple requests sent at the same time. group_name_status = {'name': '', 'status':''} def tokem_update(access_token): try: intervalInfo = UserIntervalInfo.objects.first() headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} data = {'client_id': intervalInfo.client_id, 'client_secret': intervalInfo.client_secret, 'grant_type': 'password', 'username': intervalInfo.user_id, 'password': intervalInfo.user_password } response_token = requests.post(user_token, headers=headers, data=json.dumps(data)) data = response_token.text tokens = json.loads(data) access_token.access_token = tokens['access_token'] access_token.token_type = tokens['token_type'] access_token.expires_in = tokens['expires_in'] access_token.refresh_token = tokens['refresh_token'] access_token.save() return access_token except: return False def nema_status(request): if request.method == 'POST': try: group_id = request.POST.get('group_id') access_token = API_ACCESS_TOKEN.objects.first() current_datetime = timezone.now() difference = int((current_datetime - access_token.updated_at).total_seconds() / 3600) if difference > 7: access_token = tokem_update(access_token) if access_token == False: messages.error(request, "Failed update the access token" ) else: messages.success(request, 'Successfully updated the access token') headers = { "Accept": "application/json", "Content-Type": "application/json", "Authorization": f"Bearer {access_token.access_token}" } if group_id != '0': group_name = Group.objects.get(id=group_id) if group_name.object_id: par_group_nemas_status = f"https://rpt.tvilight.io/api/status?type=group&q={group_name.object_id}" response_nema_status = requests.get(par_group_nemas_status, headers=headers) if response_nema_status.status_code == 200: datas = response_nema_status.json() nemas … -
gunicorn port already in use after reboot
I'm new to stack overflow, Django, gunicorn, and so many things... so sorry in advance for any possible violation of the rules. I'm trying to make gunicorn (running on Django) service automatically restart after rebooting the server (ubuntu 18.04). When I reboot the computer, gunicorn is enabled and running, but the problem is that the port 8000 is already in use, as described in here: Django Server Error: port is already in use I can manually kill the process and restart the gunicorn (as suggested in the solution of the above link), but I want a solution to automate this process. Any suggestions would be appreciated. Thank you. I guess I need to change some config files, but not sure what to do. I didn't develop the Django web server. Somebody created for me and I'm just using it, so I have no clue how to solve this issue. -
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?