Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Error: pg_config executable not found when deploying django app in aws
I understand this problem is common, and I've tried many solutions, none of which have worked. I'm following this tutorial to deploy a Django App to AWS EBS: https://realpython.com/deploying-a-django-app-to-aws-elastic-beanstalk/ More detail on error message from eb-engine.log: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] .ebextensions/01_packages.config: packages: yum: git: [] postgresql-devel: [] .ebextensions/02_packages.config: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py createsu" leader_only: true 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python matador-web/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "matador_web.settings" "PYTHONPATH": "/opt/python/current/app/iotd:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: matador-web/matador_web/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" .elasticbeanstalk/config.yaml: branch-defaults: feat-deploy: environment: matador-web-dev environment-defaults: matador-web-dev: branch: feat-deploy repository: origin global: application_name: matador_web branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: … -
Media Query - Django
I am trying to find a way to insert media query on Django. I want to insert them both in views.py and find a way to adapt the articles on different screens. -
how to send image file with json request?
I am working on an e-commerce project, and I want to add products from the front end. The files in my product app in Django is as follows this is my model.py: class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False) device_name = models.CharField(max_length = 50, null=True) photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) and this is my views.py @api_view(['POST']) @permission_classes ([AllowAny] , ) def addproduct(request,pk): data = request.data product = Product( price = data['price'], device_name = data['product_name'], photo = data['photo'], user = Users.objects.get(id=pk) ) if product: product.save() serializer = ProductSerializer(product,many=False) return Response(serializer.data) else: return Response({'error':'4'}) It works fine when it comes to fetching data (products I created in the Django admin) but how to send a JSON request that also contains the images and the other data ,NOTE: my views is function_based -
How to override "Cannot asign must be an instance" in Django?
I have two models: class Message(models.Model): username = models.CharField(max_length=255) room = models.CharField(max_length=255) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Notification(models.Model): notification_author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="notifauthor") notification_from = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="notiffrom") is_read = models.BooleanField(default=False) signals: @receiver(post_save, sender=Message) def create_user_notification(sender, instance, created, **kwargs): if created: Notification.objects.create( notification_author=instance.username, notification_from=instance.room) @receiver(post_save, sender=Message) def save_user_notification(sender, instance, **kwargs): instance.username.save() I am trying to create signal for creating notification after message is created. But have error: Cannot assign "20": "Notification.notification_author" must be a "Profile" instance. How to override it (if possible) without changing CharField to FK in Message model? Found smth about eval(), but it does not still work -
How to access all children for Django QuerySet
I have the following models where a Project has many Goals and a Goal has many Tasks. What is the best way to find a QuerySet containing all Tasks related to an individual Project? models.py are per below: class IndividualProject(models.Model): project = models.CharField( max_length = 64 ) def __str__(self): return f"Project {self.project}" class IndividualGoal(models.Model): goal = models.CharField( max_length = 64 ) project = models.ForeignKey( IndividualProject, on_delete=models.CASCADE, related_name="projects", blank=True, null=True, ) def __str__(self): return f"{self.goal}" class IndividualTask(models.Model): task = models.CharField( max_length = 256, blank=False, null=True, ) goal = models.ForeignKey( IndividualGoal, on_delete=models.CASCADE, related_name="goals", blank=False, null=True, ) I have tried using _set but have had no luck. I would like to use a query where I select the Project and then select a specific Task.