Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Aggregated query django manytomany field
I'm trying to make chat application where for the screen where list of messages of users are visible like the Home Screen of WhatsApp or Telegram. For which I might need Chatroom ID, Name of sender. (mainly)' I have my models set like this models.py class ChatRoom(models.Model): name = models.CharField(max_length=50) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey(User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) From where I'm querying in ChatRoomParticipants to see how many ChatRoom(s) is the user connected to. In ChatRoomParticipants user has relation with users who are connected to the that particular room. To show name and last message and the fetch ID of the ChatRoom on the mobile application I've written the following query. chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values('id','room__id', 'room__name', 'room__last_message', 'room__last_sent_user', 'user__chatroom_users__user__username')) But this gives me repeated an unexpected output which I'm not able to make any sense of Below I'm showing which 2 users are related to which room Database values room - f4253fbd-90d1-471f-b541-80813b51d610-99ea24b1-2b8c-4006-8970-2b4f25ea0f40 relations to - udaykhalsa9 and udaykhalsa7 room - f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de relations to - udaykhalsa9 and … -
Set values in summernote text editor using javascript
I want to set values in summer note text editor using JavaScript/jQuery. I have tried this both but nothing works. document.getElementById('summernote').innerHTML = data.message; $('#summernote').summernote('code', data.message); Can anyone help me how I can add values in summer note using JavaScript/jQuery. -
How to query and update Django model JsonField?
Im working on a project where using Django JSONField to store json data for the instance. When i try to query the object as per official documentation, its not working as expected. Im uanble to query the object to update the key value inside the jsonfield. Please find the below details for your reference and help to to achelve the desired result. Model class PosOrder(models.Model): store = models.ForeignKey('store.Store', on_delete=models.CASCADE, null=True) order_number = models.CharField(max_length=30, null=True) customer_phone = models.CharField(max_length=100, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) order_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_tax = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) coupon = models.ForeignKey('shoppingcoupon.ShoppingCoupon', on_delete=models.PROTECT, null=True, blank=True) order_grand_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) payment_method = models.CharField(max_length=100, null=True, blank=True, choices=( ('cash', 'Cash'), ('card', 'Card'), ('online', 'Online'))) order_status = models.CharField(max_length=100, null=True, blank=True, choices=order_status) payment_status = models.CharField(max_length=100, null=True, blank=True, choices=payment_status) payment_id = models.CharField(max_length=100, null=True, blank=True) complete = models.BooleanField(default=False) order_data = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('hrms.Employee', on_delete=models.CASCADE, null=True, blank=True) Jsonfield is like {"id": 408, "store": {"id": 1, "name": "Salt Lake"}, "order_number": "POS408", "customer_phone": "9877454577", "order_status": "processed", "payment_status": null , "payment_method": "cash", "created_at": "2022-08-09T11:38:37.207775+05:30", "created_by": {"id": 5, "code": "RMS003"}, "get_order_total": 39206, "get_order_tota l_discount_amount": 2232, "get_order_total_without_tax": 32730, "get_order_total_tax": 6476, "ordered_items": [{"id": 41, "item": {"id": 3, "product": {"id": 3, … -
How can translate the the whole screen language of application by only clicking single click on lang selection using python for flutter application
I have a Flutter app with 100 language choice on login page. I want when user choose one language suppose "Hindi" language the language of whole application screen should change. How can I change the language of whole application. -
How to add value in blank query set
I am running last 6 months of report which contains month, visits, fees and other fees as fields. When a month not having any visits its shows empty query set. how to pass a value to empty query set. I am getting result as below: <QuerySet [{'month': 7, 'visits': 19, 'fees1': Decimal('6380'), 'other_fees': Decimal('1730')}]> <QuerySet [{'month': 6, 'visits': 6, 'fees1': Decimal('3201'), 'other_fees': Decimal('851')}]> <QuerySet [{'month': 5, 'visits': 6, 'fees1': Decimal('900'), 'other_fees': Decimal('1685')}]> <QuerySet []> <QuerySet [{'month': 3, 'visits': 2, 'fees1': Decimal('455'), 'other_fees': Decimal('605')}]> <QuerySet [{'month': 2, 'visits': 2, 'fees1': Decimal('430'), 'other_fees': Decimal('504')}]> month 4 is not having any visit and fees since, the query set being empty. instead of empty. I want to set value of 0 for the fields. -
Error Deployment of Web Application using Django and Heroku
-----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
How to add 'django.contrib.auth' app in django
I deployed Django project using cloud code from pycharm. but in this sample template, there were not the code in installed_app basic apps like these 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', there was only 'django.contrib.staticfiles' apps. Also the default middleweres were not completely installed INSTALLED_APPS = [ 'django.contrib.staticfiles', 'helloapp', ] MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So, is there any way to use default apps to make login page.? -
How to Configure Celery and Celery Beat with Django deployed on Elastic Beanstalk Amazon Linux 2
Hi I'm new to celery, I was wondering if some can help me with my question. In our Django web app, there are some background tasks that we want to run every midnight. With this, I tried celery with celery beat. I was able to successfully implement background task scheduler with celery beat and worker with Redis as Celery broker following the tutorial on: https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#using-celery-with-django https://docs.celeryq.dev/en/latest/userguide/periodic-tasks.html The feature is working locally by running the servers, scheduler and workers accordingly on separate terminals. Django Server `python manage.py runserver` Redis Server `redis-server` Celery Worker `celery -A django_project.celery beat -l info` Celery Beat Scheduler `celery -A django_project worker -l info` My question is how do I configure this for deployment in Elastic Beanstalk? What is the correct way to set this up properly with Elasticache as the Redis server? Current Stack: Django 3.1 deployed on AWS Elastic Beanstalk Python 3.8 running on 64bit Amazon Linux 2/3.3.9 with ElastiCache endpoint redis==4.3.4 # https://pypi.org/project/redis/ celery==5.2.7 # https://pypi.org/project/celery/ Any help is much appreciated! -
Django query: FOR EACH month AND name SUM values
What I need: for each month, I need to get the total sales (SUM) from John and Mary. There are other people in the database, but I only need info from both of them. [ ["19-Nov", "John", 511.97], ["19-Nov", "Mary", 0], ["19-Dec", "John", 568.21], ["19-Dec", "Mary", 1542.08], ["20-Jan", "John", 621.20], ["20-Jan", "Mary", 401.06], ["20-Feb", "John", 621.39], ["20-Feb", "Mary", 0], ["20-Mar", "John", 0], ["20-Mar", "Mary", 871.14], ["20-Apr", "John", 604.25], ["20-Apr", "Mary", 653.34], ["20-May", "John", 584.94], ["20-May", "Mary", 1218.43], ] The date must be formatted in this "Year-Month" type in order (oldest to newest ones). The total sales, even if it's zero, must be printed. My Django model: class Sellers(models.Model): date = models.DateField() name = models.CharField(max_length=300) value = models.DecimalField(max_digits=19, decimal_places=2) Is it possible to create just one Django query to retrieve data in this format? Tks! -
How to implement dropdown search bar in Django?
I am thinking of a way how to implement dropdown search bar on my application, this is just the simplest form of it, given: models.py CATEGORY = ( ('Hard Disk Drive', 'Hard Disk Drive'), ('Solid State Drive', 'Solid State Drive'), ('Graphics Card', 'Graphics Card'), ('Laptop', 'Laptop'), ('RAM', 'RAM'), ('Charger', 'Charger'), ('UPS', 'UPS'), ('Mouse', 'Mouse'), ('Keyboard', 'Keyboard'), ('Motherboard', 'Motherboard'), ('Monitor', 'Monitor'), ('Power Supply', 'Power Supply'), ('Router', 'Router'), ('AVR', 'AVR'), ('Tablet', 'Tablet'), ('System Unit', 'System Unit'), ('Audio Devices', 'Audio Devices'), ('CPU', 'CPU'), ('Others', 'Others'), ) class Product(models.Model): model_name = models.CharField(max_length=100, null=True, blank=True) asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['model_name', 'asset_type'] views.py def product(request): items = Product.objects.all() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = ProductForm() context = { 'items': items, } return render(request, 'products.html', context) products.html <div class="container"> <div class="row my-1"> <h4>Enroll a product:</h4> <hr> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-success btn-block" type="submit" value="Add Product"> <button type="button" class="btn btn-danger btn-block">Close</button> </form> </div> We all know that the result of the form (in HTML) when showing the categories of the model Product(asset_type) is a dropdown field with no search bar on … -
With Django, connecting a User to a completed Form?
right now, users can view all forms that are completed by any user, even when they are logged in and all forms get posted onto the same html page. I want users to only be able to view their own forms they completed when logged into their account. Any directions would be helpful. I understand functions more than classes in views, an Ideal solution would use functions. Thank you sooo much for any advice as this is my first Django I am trying on my own without strictly following a video or class. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm from django import forms class Step1_Model(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = "STEP 1: Safety during a violent incident" box1 = models.CharField(max_length=100, null=True) box2 = models.CharField(max_length=100, null=True) box3 = models.CharField(max_length=100, null=True) box4 = models.CharField(max_length=100, null=True) box5 = models.CharField(max_length=100, null=True) box6 = models.CharField(max_length=100, null=True) def __str__(self): return self.title forms.py from django import forms from .models import Step1_Model class Step1_Form(forms.ModelForm): box1 = forms.CharField() class Meta: model = Step1_Model #which model we want to use as a model for our model form fields= ("box1","box2","box3", "box4", "box5", "box6") views.py from django.shortcuts import render, redirect from django.contrib import … -
Prevent admin url from being overridden Django
I have a urls file that looks like this, however I cannot access the admin page. Is there any way to specify that the admin URL should never be overridden? from django.contrib import admin from django.urls import path from latency import views urlpatterns = [ path("admin/", admin.site.urls), path("<str:chain>", views.regions), path("<str:chain>/<str:region>", views.chain), path("", views.index), ]``` -
Django ProgrammingError must appear in the GROUP BY clause or be used in an aggregate function using annotate func
Here is my model. class EnvAi(models.Model): dateandtime = models.CharField(db_column='DateAndTime', max_length=50, blank=True, null=True) # Field name made lowercase. tagname = models.CharField(db_column='TagName', max_length=50, blank=True, null=True) # Field name made lowercase. datavalue = models.CharField(db_column='DataValue', max_length=50, blank=True, null=True) # Field name made lowercase. dateandtime sample is "2022-08-10 10:10:20" dateandtime field is charField and i have to slice date and time. # views.py queryset = EnvAi.objects.values('datavalue', 'tagname').annotate(slicedate=Substr('dateandtime', 1, 10)) # slicedate => "2022-08-10" # Error Code queryset = queryset.values('tagname', 'slicedate').annotate(max_value=Max('datavalue')) after create 'slicedate' variable, I want to get Max value each tagname and slicedate. but i get error ProgrammingError: column "Env_AI.DateAndTime" must appear in the GROUP BY clause or be used in an aggregate function I tried using raw sql in the database using query, but there was no problem. How can i solve this problem? -
Why aren't my images showing up after following Django's documentation on static files?
I'm having some trouble displaying images in a website I'm building. I am following the instructions in the Django static files documentation. To wit, I have: Verified that my settings.py file contains STATIC_URL = 'static/' Added the equivalent of the following code to my template: {% load static %} <img src="{% static 'my_app/example.jpg' %}" alt="My image"> Stored my images in `my_app/static/my_app/ I get no error when I navigate to the relevant page. Just an empty div where the image should be. It seems like in the past, this problem has been solved by using render() (example). However, I'm using Django 4.x, as well the render() function. Why aren't my images showing up? -
How to convert this XML to a table in Django?
I am brand new to coding, but have been given a task to convert some XML files to a table and present them in an existing Django environment. I honestly don't know where to begin, especially since the XML I'm trying to convert is a bit strange. Below is an example snippet. You'll see the information is stored as element attributes rather than content: <?xml version="1.0" encoding="UTF-8"?> <object_list> <object no_step="0" id="First Object" cd_type="SYSTEM" cd_outcome="" dt_create="2022-03-04 15:31:39.965" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="1" id="Second Object" cd_type="Ruleset" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.981" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="2" id="Third Object" cd_type="AppWriter" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.981" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="3" id="Forth Object" cd_type="Ruleset" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.997" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> <object no_step="4" id="Fifth Object" cd_type="WebService" cd_outcome="Commence" dt_create="2022-03-04 15:31:39.997" tx_flow="FLOW_1" tx_creditproduct="Consumer Product"> </object> </object_list> What I need to convert this to is a table, like this: table example Can anyone point a beginner in the right direction for how to achieve this using Python / Django? Thank you in advance! -
Concatenate two parameters [duplicate]
I have a python function that is receiving two parameters. I want to combine these two parameters to create the reference to a field in the model/db. The first parameter is an object of the model. The second is a string that contains the field name. I want to combine them in order to reference the field name. This code, of course, does not work, but it should show what I'm trying to accomplish. x = image_reference(parent, 'name') def image_reference(parent, field_string): db_image = parent.+field_string The value of db_image I'm looking to achieve would be parent.name, which allows me to reference the field called name in the model. Thank you in advance. -
How do I name Django ManyToMany object relations in Django admin?
Is there a way to give the relations their name instead of calling them "object-n" like shown below? Here is the code for the two models in question: class jobTag(models.Model): Tag = models.CharField(max_length=15) def __str__(self): return self.Tag class job(models.Model): Company_name = models.CharField(max_length=200, null=True, blank= True) Position = models.CharField(max_length=200, null=False, blank=False) Type = models.ForeignKey(jobType, default=" ",verbose_name="Type", on_delete=models.SET_DEFAULT) Industry = models.ForeignKey(jobIndustry, default=" ", verbose_name="Industry", on_delete=models.SET_DEFAULT) Location = models.ForeignKey(jobLocation, default=" ", verbose_name="Location", on_delete=models.SET_DEFAULT) Role_description = tinymce_models.HTMLField(default="") Role_requirements = tinymce_models.HTMLField(default="") Role_duties = tinymce_models.HTMLField(default="") Special_benefits = tinymce_models.HTMLField(default="") Date_posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField('jobTag', related_name="job-tags+", blank=True) def time_posted(self): return humanize.naturaltime(self.Date_posted) def __str__(self): return self.Position class Meta: verbose_name_plural = "Jobs" Thanks in advance. -
How to convert synchronous code to async Python?
I have been working on a code that would create owners and lots and assign lots to each owner. While I got the code to work, it takes too long to run and was thinking about improving it by making it asynchronous. I have been watching a few videos and reading resources online but I am still confused as to how to implement this. I was wondering if it would be possible for someone to guide me how to accomplish this feat and optimize my code for performance. Here is the code below: def handle_csv(csv): database = pd.read_csv(csv) lot= database[['lot_description','lot_number', 'lot_rate']] owner = database[['account_number', 'first_name', 'last_name', 'occupation']] address = database[['area','lot_number', 'account_number','street_name', 'street_number']] for index in database.index: try: owner_new = Owner.objects.get(pk=owner["account_number"][index]) except: owner_new = Owner.objects.create( account_number=owner["account_number"][index], first_name= owner["first_name"][index], last_name= owner["last_name"][index], ) owner_new.save() try: lot_new = Lot.objects.get(pk=lot["lot_number"][index]) except: lot_new = Lot.objects.create( lot_number=lot["lot_number"][index], lot_description= lot["lot_description"][index], ) lot_new.owner.add(owner_new) lot_new.save() -
Django Model function behavior changes based on how many tests being run
I have a need for a uniqueID within my Django code. I wrote a simple model like this class UniqueIDGenerator(models.Model): nextID = models.PositiveIntegerField(blank=False) @classmethod def getNextID(self): if(self.objects.filter(id=1).exists()): idValue = self.objects.get(id=1).nextID idValue += 1 self.objects.filter(id=1).update(nextID=idValue) return idValue tempObj = self(nextID=1) tempObj.save() return tempObj.nextID Then I wrote a unit test like this: class ModelWorking(TestCase): def setUp(self): return None def test_IDGenerator(self): returnValue = UniqueIDGenerator.getNextID() self.assertEqual(returnValue, 1) returnValue = UniqueIDGenerator.getNextID() self.assertEqual(returnValue, 2) return None When I run this test by itself, it runs fine. No issues. When I run this test as a suite, which includes a bunch of other unit tests as well (which include calls to getNextID() as well), this test fails. The getNextID() always returns 1. Why would that be happening? -
Django Multiple user type
I have different types of users where I have to collect different types of information from different types of users. Eg:- if the user is accountant the required information would be id proof; if the user is executive the required information would be id proof and other personal details; if the user is client the required information would be official details like Company name, company id, etc. Please help me out in this. Thank you in advance. -
ImportError: attempted relative import with no known parent package. Python packages
... File "/Users/mammadaliyevmammadali/Desktop/dev/ecom/apis/tasks.py", line 12, in create_fake_phone from .models import Phone ImportError: attempted relative import with no known parent package module layout # tasks.py from random import choice from faker import Faker from celery import shared_task from .models import Phone # error occurs here fake = Faker() @shared_task def create_fake_phone() -> None: Phone.objects.bulk_create([ Phone( ... ) for _ in range(10) ]) I get this error when I just try to run tasks.py file. What is the matter here, guys? Why I am getting this error. Please help! -
How to get the field definition by name of related objects in Django
I need to retrieve the field of related objects of a model by name. For example if Book has a ForeignKey field to Author called author, I would like to be able to something like: field = 'author__name' Book._meta.get_field(field).verbose_name It is general purpose so that string author__name is not known in advance -- I can't hardcode the fields or traversal. Furthermore, it may span more than one relation like author__address__city if there was a fk to an Address model on the Author. _meta.get_field() returns MODEL has no field named FIELD when I try such a field name with fk traversal. Django must have ways of doing this as these traversals must be done internally all the time, but I could not find how in the docs or looking into the code. Any ideas appreciated! -
Python Django, unit test for functions?
In a Python Django project, the function retrieve_timerange(request) is not a member of any class and contains an embedded function parse_timestamp(datetime_str). I want to write unit tests to cover the boundary conditions, e.g. entering and leaving Summer Daylight Saving Time in the local time zone. I am wondering: How to write the unit test for the function retrieve_timerange(request)? How to write the unit test for the embedded function parse_timestamp(datetime_str)? I generated the below unit test test_service.py by PyCharm, and it runs. However, I don't see any connection to the functions under test. I don't know how to feed input to the function call and verify the return. I am new to unit test writing, so I would highly appreciate any hints or suggestions. Partial sample source code of service.py: from django.utils import timezone from dateutil.parser import isoparse import datetime ... def retrieve_timerange(request): def parse_timestamp(datetime_str): ... return timestamp ... time_from = None time_to = None if query_params is not None: time_from = parse_timestamp(str_time_from) time_to = parse_timestamp(str_time_to) return time_from, time_to ... Sample unit test source code of test_service.py: from unittest import TestCase import unittest import dateutil import pytz class Test(TestCase): def test_parse_timestamp(self): self.fail() -
connect() to unix:/home/glenn/blog.sock failed (13: Permission denied) while connecting to upstream
I am trying to connect my django project to a gunicorn socket using Nginx (ubuntu 22.04) server, and I think my configuration file is okay. However when I try to go to my Ip address on the server I get a 502 getway error. When I check the error log, I get the following output: 2022/08/09 22:05:36 [crit] 7960#7960: *5 connect() to unix:/home/glenn/blog.sock failed (13: Permission denied) while connecting to upstream, client: 197.231.183.74, server : 67.205.168.227, request: "GET / HTTP/1.1", upstream: "http://unix:/home/glenn/blog.s ock:/", host: "67.205.168.227" I have followed the documentation to check for possible troubleshooting guides, and I have been adviced to check for my permissions. On doing so, I get the following error log drwxr-xr-x root root / drwxr-xr-x root root home drwxr-x--- glenn glenn glenn srwxrwxrwx glenn www-data blog.sock So does anyone know of a specific command I can use to edit the permissions? Or how I can edit my configuration file to change the permissions here is how my sites-available file looks like server { listen 80; server_name 67.205.168.227; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/glenn/blog; } location /media/ { root /home/glenn/blog; } location / { include proxy_params; proxy_pass http://unix:/home/glenn/blog.sock; … -
Notification from sql new object when user login - Django
My query is the next: How can I display a notification to a user who logged for the first time after the action that created the notification has been executed. In my case I want the user to get notified when he win something.