Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordering is not working for string numerical values
I have a text field(Django) for the amount in the DB like amount = models.TextField(null=True, blank=True) SQL query select id, amount from payment order by amount asc; id | amount | -------+---------+ 12359 | 1111111 | ----> entered as "1111111" i.e a string value 12360 | 122222 | 12342 | 20 | 12361 | 222222 | 12364 | 2222222 | 12362 | 2222222 | 12290 | 260.00 | 12291 | 260.00 | 12292 | 260.00 | 12336 | 32 | 12363 | 3333333 | 12337 | 355 | 12331 | 45 | 12341 | 740 | 12343 | 741 | Problem - Ordering is not working as expected. Is it the expected behavior? -
jquey DataTable Ajax add extra column empty value
I have this javascript function: $(document).ready(function() { var table = $('#ourtable2').DataTable({ language: { url: '//cdn.datatables.net/plug-ins/1.13.3/i18n/it-IT.json', }, "ajax": { "processing": true, "url": "{% url 'ausers' %}", "dataSrc": "", }, "columns": [ { "data": "id"}, { "data": "username"}, { "data": "first_name"}, { "data": "last_name"}, { "data": "email"}, { "data": "is_staff"}, { "data": null, "render": function ( data, type, row, meta ) { return '<a href="" onClick="editFunc('+data['id']+')">Modifica</a>'; } }, ], }); }); The issue is that data['id'] is empty What is wrong ? How can i retrieve the value of id ? -
How to use Django to search database and display info in web application?
I'm currently working on a data visualization board. Cyber Security Data Visualization I know a few things about creating classes in models.py, objects in views.py, and putting the value of objects in an HTML file. But the best fuzzy search I know is like this: isc_2022 = Isc.objects.filter(issue_date__startswith='2022').count() This only gets a count number, but now I want to put information in HTML file through Django. The information is specially selected and ordered like this: Search MySQL It is not hard for Python to get a list from a database, here is how I do it: import pymysql connection = pymysql.connect( host="localhost", user='root', password='xxxxxx', database='project', ) cursor = connection.cursor() cursor.execute("""SELECT company, COUNT(*) AS count FROM cc_statistic GROUP BY company ORDER BY count DESC LIMIT 5;""") myresult = cursor.fetchall() mylist = [] for x in myresult: mylist.append(x) print(mylist) But how can Django do this and dynamically connect the values with my web application? And more importantly, is there any better way than asking on Stack Overflow to obtain knowledge like this? I find the official document for Django, like other documentation for other libraries, not easy to use. And they don't always have the thing I want. Thank you for spending … -
How to add an exmaple to swagger_auto_schema in django rest framework?
I am working with @swagger_auto_schema for documenting APIs in django-rest-framework. I want to add examples for both input and output. here is my code for one of the APIs. from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema @swagger_auto_schema( methods=['post'], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['name', 'lastname', 'username', 'password', 'confirm_password'], properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, max_length=50), 'lastname': openapi.Schema(type=openapi.TYPE_STRING, max_length=50), 'username': openapi.Schema(type=openapi.TYPE_STRING, description="it must be unique for every person. it must not contain space or invalid characters."), 'password': openapi.Schema(type=openapi.TYPE_STRING), 'confirm_password': openapi.Schema(type=openapi.TYPE_STRING, description="password and confirm password must be same"), 'national_code': openapi.Schema(type=openapi.TYPE_STRING), 'license_code': openapi.Schema(type=openapi.TYPE_STRING), 'birthdate': openapi.Schema(type=openapi.TYPE_STRING, default="yyyy-mm-dd", description="it is actually a date"), 'gender': openapi.Schema(type=openapi.TYPE_INTEGER, enum=[(1, _("Male")),(2, _("Female"))]), 'address': openapi.Schema(type=openapi.TYPE_STRING), 'email': openapi.Schema(type=openapi.TYPE_STRING), 'phone_number': openapi.Schema(type=openapi.TYPE_STRING), 'image_code': openapi.Schema(type=openapi.TYPE_STRING, description="it is the base64 code of the image"), }, # One example for a correct body ), responses={ 200: 'Staff Created Successfully!', # One example for 200 status code 400: 'Error!', }, operation_description="Add a new staff API. The role field(=staff), customer field(=parent.customer) and parent would be set automatically", ) And this is the rendered schema in swagger. But I want to add two read only JSONs jsut for rendering the correct input and the desired output. I will be grateful for any helpful link or examples. -
Has anyone figured out how to create a Django Persistent Connection or SSE?
I'm trying to create a web application for ordering food where a kitchen logs into a webpage and then receives real time updates on the orders. Ideally they would just leave the webpage open for 12-24 hours at a time. Can websockets do that? I've been trying to get django_eventstream to work, but there are so little examples and explanations on how to get it to work, has anyone been successful at this? -
Django-admin/Python manage.py makemessages gives error and deletes already translated msgstr
Basically i have been facing this issue for about 3 days, I have been trying to run the command line: python manage.py makemessages -l ar Which usually should work, however, its lately been deleting lines from Django.po in which if I compilemessages it causes the system to crash with multiple errors. When running python manage.py makemessages -l ar , I get some warning that I have never seen before on older translations, the warnings that i get is: warning: The following msgid contains non-ASCII characters. This will cause problems to translators who use a character encoding different from yours. Consider using a pure ASCII msgid instead. This is truly annoying and its causing me to bash my head around for hours, would appreciate the help. EDIT: After redoing the translation again from the start, I had to again do makemessages for new lines, and guess what?, the same error appeared and deleted all the changes I made. I would appreciate some help. That it would just refractor and add the new lines to be translated rather than delete 3 years of work. -
I want create conditional questions Django and Graphql
I did not now how create this logic. Form example we have different stages and in this stages we have some conditional questions it look like for example If the user selects I have no education in the 4th question, the stage about education should not be shown to him, if he chooses I have education, the stage about education should be shown. In front I use React in backend i use django graphql. can someone give mee some advise -
Image from database to send in whatsapp
Now I want to take orders on WhatsApp number for that I have used pywhatkit when i visit particular product detail, i want image of product to send from database, iam facing problem in that I have used pywhatkit module to send product detail, now I want image also to appear while sending WhatsApp msg but Iam getting only text related to product and image URL and path I am getting instead of image -
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