Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to load second element list on selection on first element in Django forms
How do I load university list based on selected country. In the attached image I am getting all the country universities. Forms.py countries_list=list(Countries.objects.all().values_list('id','name')) universities_list=list(Universities.objects.all().values_list('id','name')) class ConsolidatedSheetDownloadForm(forms.Form): countries = forms.ChoiceField(choices=countries_list, required=True,error_messages={'required': 'Select country to proceed'}) universities = forms.MultipleChoiceField(choices=universities_list, required=True,error_messages={'required': 'Select university to proceed'}) https://i.stack.imgur.com/8ANvb.png -
Deploy Django app to Heroku end with Error
Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tailenter code here Log file: 2022-01-25T09:56:52.826338+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2022-01-25T09:56:52.826405+00:00 app[web.1]: self.reap_workers() 2022-01-25T09:56:52.826413+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2022-01-25T09:56:52.826514+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2022-01-25T09:56:52.826544+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2022-01-25T09:56:53.005213+00:00 heroku[web.1]: Process exited with status 1 2022-01-25T09:56:53.060263+00:00 heroku[web.1]: State changed from starting to crashed 2022-01-25T09:56:58.000000+00:00 app[api]: Build succeeded 2022-01-25T09:57:06.746469+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sheikhshahed.herokuapp.com request_id=5096cca5-60ee-4038-b90a-30ab5d4b13fe fwd="106.0.54.74" dyno= connect= service= status=503 bytes= protocol=https 2022-01-25T09:57:07.638428+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sheikhshahed.herokuapp.com request_id=245c9fab-4633-4387-805b-3255291496c6 fwd="106.0.54.74" dyno= connect= service= status=503 bytes= protocol=https -
Django: User login not works for some users
I'm currently learning django. Here is my problem: user created using terminal with createsuperuser can log in to the website, but users created with my register page are not. Users created using my registration appear in the admin panel and all fields match the entered data. I guess the problem is somewhere in CustomUserManager(before creating it login worked properly) models.py class CustomUserManager(BaseUserManager): def create_superuser(self, email, username, first_name, bio, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError("Superuser must be assigned staff to True") if other_fields.get('is_superuser') is not True: raise ValueError("Superuser must be assigned superuser to True") return self.create_user(email, username, first_name, bio, password, **other_fields) def create_user(self, email, username, first_name, bio, password, **other_fields): if not email: raise ValueError("You must provide an email.") email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, bio=bio, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=200, null=True, verbose_name="Имя") username = models.CharField( max_length=50, null=True, verbose_name="Никнейм", unique=True) email = models.EmailField(null=True, unique=True) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(null=True, default="avatar.svg", blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','username','bio'] def __str__(self): return self.username views.py def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == … -
how do I transfer data from a form to another page immediately?
Help, please! I'm writing a simple donation site in Django. I want to use LiqPay payment system. I've described a form which takes data from user (def donation), but I can't figure out how to pass this data to another function (class PayView, def get) I've tried creating a user and then taking the 'amount' field from it, but I don't want to force users to register. 'PayView' is rendered immediately after 'submit' in 'def donation' My code: views.py def donation(request): if request.method == 'POST': form = CheckoutForm(request.POST) if form.is_valid(): Donation.objects.create(**form.cleaned_data) return redirect('pay_view') else: form = CheckoutForm() return render(request, 'donation/donation.html', {'form': form}) class PayView(TemplateView): template_name = 'donation/pay.html' def get(self, request, *args, **kwargs): liqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY) params = { 'action': 'pay', 'amount': '1', 'currency': 'UAH', 'description': 'Допомога фонду', 'order_id': 'order_id_1', 'version': '3', 'sandbox': 1, # sandbox mode, set to 1 to enable it 'server_url': '', # url to callback view } signature = liqpay.cnb_signature(params) data = liqpay.cnb_data(params) return render(request, self.template_name, {'signature': signature, 'data': data}) forms.py from django import forms class CheckoutForm(forms.Form): amount = forms.IntegerField() first_name = forms.CharField() last_name = forms.CharField() phone = forms.CharField() email = forms.EmailField() Sorry for the silly question. I am very new to this. Thanks! -
Downgrade django version from 3.2 to 1.8 [closed]
my project is developed on django 3.2 now i want to downgrade it to version 1.8 because it needed. What would be the best course of action for achieving that? I tried by changing version in requirement.txt got compatibility error of django with other module. -
Why am i getting this error when i run python manage.py shell in terminal? [closed]
File "c:\users\hp\appdata\local\programs\python\python39\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined> -
Why can't I see my NGINX log's when my app is deployed to Azure app services, but it works fine locally?
I have a Dockerized Django application, which I'm orchestrating with Supervisor, which is not optimal but needed when hosting on Azure app services as their multi-app support with docker-compose is still in preview mode (aka. beta). According to best-practises I have configured each application within supervisord to emit the logs to STDOUT. It works fine when I create the Docker image locally, run it and check the docker logs. However, when I have deployed it to Azure app services and check the logs, my web-application (Gunicorn) is logging as expected, however, the logs from NGINX don't appear at all. I have tried different configurations in my Dockerfile for linking the log files generated by NGINX (linking to both /dev/stdout and /dev/fd/1 for example) and I have also gone into the the nginx.conf config and trying to log out directly to /dev/stdout. But whatever I do it work fine locally, but on Azure the logs don't show any NGINX-logs. I've pasted relevant configuration files, where you can see the commented lines with the options I've tried with. Hope someone can help me figure this one out. Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 ################### # PACKAGE INSTALLS ################### RUN apt-get update RUN … -
How to resolve django-q qcluster type error?
I'm trying to set up scheduled tasks in my django server using qlcuster following this tutorial. Some objects in my database have an expiration date field that is set for each new object, so I want to have a worker checking every day for the objects past their expiration date and remove them. My task is written as follows : from datetime import datetime from .models import MyObject def delete_expired_objects(): """ Deletes all objects expired """ expired_obj = MyObject.objects.filter(expirationDate__lte=datetime.today()) expired_obj.delete() The schedule is set no problem, but when running the scheduler it throws some errors saying that the type is incorrect as it is apparently not expecting a string : Message: TypeError('unsupported type for timedelta seconds component: str') Arguments: ('Traceback (most recent call last):\n File "/usr/local/lib/python3.10/site-packages/django_q/cluster.py", line 345, in pusher\n task_set = broker.dequeue()\n File "/usr/local/lib/python3.10/site-packages/django_q/brokers/orm.py", line 64, in dequeue\n tasks = self.get_connection().filter(key=self.list_key, lock__lt=_timeout())[\n File "/usr/local/lib/python3.10/site-packages/django_q/brokers/orm.py", line 14, in _timeout\n return timezone.now() - timedelta(seconds=Conf.RETRY)\nTypeError: unsupported type for timedelta seconds component: str\n',) Is there a way to give it an int while still checking if the date is older than today ? -
how to save a model object in another model save method
I have user model that has a one to one relation with two other models. these are my models: class User(AbstractUser): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) isPreRegistered = models.BooleanField(default=False) username = models.CharField(unique=True, max_length=13) first_name = models.CharField(max_length=32, null=True, default=None) last_name = models.CharField(max_length=64, null=True, default=None) progress_level = models.CharField(max_length=25, null=True, choices=USER_PROGRESS_LEVELS) class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) final_assessment = models.TextField(null=True, blank=True) is_interviewed = models.BooleanField(default=False) class PsychologicInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) final_assessment = models.TextField(null=True, blank=True) is_interviewed = models.BooleanField(default=False) I want to update the user's progress_level if PsychologicInfo.is_interviewed and ScientificInfo.is_interviewed are both True. So I thought I should override the save method and added this to the user model: def save(self, *args, **kwargs): if self.scientificinfo.is_interviewed == True and self.psychologicinfo.is_interviewed == True: self.progress_level = USER_PROGRESS_LEVELS[1][0] return super(User, self).save(*args, **kwargs) But I have to save the User object one more time to see some results. how can I update my progress level field when PsychologicInfo and ScientificInfo get saved? -
Strange module behavior djangoql
We use djangoql for easy search in our django admin panel. The mixin DjangoQLSearchMixin has been added to some of our models in the admin panel. And sometimes after deployment we get an error in the handler application_name/model_name/introspect/ Error: FieldDoesNotExist at /admin/user/user/introspect/ Model_name has no field named 'field_name' After the reboot, the error disappears. The error cannot be reproduced locally. -
Django filter JSONField when key is a number
node_status is JOSNField, how to filter node_status of queryset has key '2'==True >>> instance.node_status {'cat': '1', '2': True, 'dog': True} >>> qs.filter(node_status__cat=1) Yeah got result >>> qs.filter(node_status__has_key='dog') Yeah got result >>> qs.filter(node_status__2=True) <QuerySet []> node_status__2=True got empty queryset. -
how to use Django channels in another clients?
I have created a chat program with Django channels I want to use this program on another client such as Android or desktop With JavaScript, we can create sockets, connect chat programs, and send and receive messages I want to know how can I use the chat program on another client? Do I need to create an api for the chat app? Or is everything created in a client program like JavaScript? Do I need to create an api for my app? -
Is request available inside django to_representation serializer method?
I am trying to perform a request check inside the to_representation serializer method in django but the self.context is always empty. Any ideas why? class TwitterAccountsListsSerializer(serializers.ModelSerializer): class Meta: model = TwitterAccountsList fields = ["id", "name", "created_at", "is_private", "accounts"] extra_kwargs = { "accounts": {"write_only": True}, } def to_representation(self, instance): import pdb; pdb.set_trace() # self.context is always an empty dict here {} return super().to_representation(instance) -
How to uninstall apscheduler from Django project?
I have apscheduler configured with a single task in a Django project. The task was just to test apscheduler capabilities. Now I need to uninstall it completely. How do I do that? I guess pip uninstall apscheduler is not enough? -
Need Help in adding an email notification in Django
I am trying a timesheet project. I am using Django rest-framework and using Postgres as my database. My client requested me this ( If a user already existed in the database or a new user is creating their account an email should be triggered when the post option was submitted in rest API ). Below I'll include my codes models.py from django.http import HttpResponse, HttpResponseRedirect, response from django.db import models from django.db.models.deletion import CASCADE from django.utils import timezone from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from django.core.mail import send_mail from django.db.models import signals import datetime from django.core.mail import EmailMessage class User(models.Model): CHOICES= ( ('manager','Manager'), ('hr', 'HR'), ('hr manager','HR Manager'), ('trainee','Trainee') ) firstname = models.CharField(max_length=210) lastname = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) password=models.CharField(max_length=100,default=None) joiningDate=models.DateTimeField(max_length=8) userrole=models.CharField(max_length=20,choices=CHOICES,null=True) def __str__(self): return self.firstname class Project(models.Model): name = models.CharField(max_length=20) description=models.TextField() type=models.TextField() startDate = models.DateTimeField(max_length=10) endDate=models.DateTimeField(max_length=10) user=models.ManyToManyField(User) def __str__(self): return self.name class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date=models.DateField() Hours=models.TimeField(null=True) def __str__(self): return self.id class Client(models.Model): clientname=models.CharField(max_length=20) comapny=models.CharField(max_length=200) location=models.CharField(max_length=200) email=models.EmailField(max_length=25,default=None) def __str__(self): return self.clientname serializers.py from django.db.models import fields from rest_framework import serializers from.models import User,Project,Timesheet,Client class UserSerializers(serializers.ModelSerializer): class Meta: model= User fields ='__all__' password = serializers.CharField(max_length=128, write_only=True, required=True) class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project … -
Django-JqueryUI Date Picker remove specific Dates which is passed as Django context
I have a django project which passes dates as dictionary to my template,Previuosly i used select to pick date but that doesnt look good and I decided to replace it with a datepicker which has dates only present in that disctionary.I tried several ways but could not wrap around it.Please help html: <div id="datepicker"></div> script: $(function() { $( "#datepicker" ).datepicker(); }); views.py: available_dates={'2022-01-25': 'Tue', '2022-01-26': 'Wed', '2022-01-27': 'Thu'} return render(request,'datepicker.html',{'dates':availabe_dates}) And I was using ajax with my select to retrive my data back to backend: <select onchange="return sendData(this.value)" and here's my ajax code: function sendData(date){ $.ajax({ type : "POST", url: "", data: { date : date, csrfmiddlewaretoken:'{{ csrf_token }}', }, And now i want to replace select with datePicker with all this functialities,But i dont know how to begin,So please Help -
Unable to dockerize django
I am new to Docker, I have tried several video samples on youtube, yet I am unable to dockerize django app using anaconda Here is my Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app Here is docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Here is requirements.txt asgiref 3.4.1 pyhd3eb1b0_0 ca-certificates 2021.10.26 haa95532_2 certifi 2021.10.8 py39haa95532_2 django 3.2.5 pyhd3eb1b0_0 krb5 1.19.2 h5b6d351_0 libpq 12.9 hb652d5d_1 openssl 1.1.1m h2bbff1b_0 pip 21.3.1 pypi_0 pypi psycopg2 2.8.6 py39hcd4344a_1 python 3.9.7 h6244533_1 pytz 2021.3 pyhd3eb1b0_0 setuptools 58.0.4 py39haa95532_0 sqlite 3.37.0 h2bbff1b_0 sqlparse 0.4.1 py_0 typing_extensions 3.10.0.2 pyh06a4308_0 tzdata 2021e hda174b7_0 vc 14.2 h21ff451_1 vs2015_runtime 14.27.29016 h5e58377_2 wheel 0.37.1 pyhd3eb1b0_0 wincertstore 0.2 py39haa95532_2 zlib 1.2.11 h8cc25b3_4 After running "docker-compose build" I get this error message => ERROR [5/6] RUN pip install -r requirements.txt 3.1s ------ > [5/6] RUN pip install -r requirements.txt: #10 2.240 ERROR: Invalid requirement: 'asgiref 3.4.1 pyhd3eb1b0_0' (from line 4 of requirements.txt) #10 2.933 WARNING: You are using pip version 21.2.4; however, version 21.3.1 is available. #10 2.933 You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command. … -
Django template is not deleting the record correctly
This is my template code <tbody> {% for item in items %} <tr class="text-black"> <td>{{ item.name }}</td> <td>{{ item.description }}</td> <td> <a href="{% url 'menu-options-update' item.id %}" class="btn btn-sm btn-user edit" > <!-- <i class="far fa-edit"></i> --> <i class="fas fa-pencil-alt"></i ></a> <a data-toggle="modal" class="btn btn-sm btn-user delete btn--show-modal" href="#myModal" data-confirm="Are you sure to delete this item?" ><i class="fas fa-trash"></i ></a> </td> <div class="modal1 hidden"> <button class="btn--close-modal">&times;</button> <h2 class="modal__header">Do you want to delete this record?</h2> <div class="deletModalBtnContainer"> <a href="{% url 'menu-options-delete' item.id %}" class="delete-final btn" >Delete</a > <a href="#" class="cencel-modal btn btn-cancels-close-modal" >Cencel</a > </div> </div> </tr> {% endfor %} </tbody> And this is my view item = MenuOptions.objects.get(id=id) item.delete() This code is always picking the 1st id in the table data, not the one on which I have clicked. Let's suppose my table has 5 rows and I want to delete the 4th row but after I click on the delete button it is deleting the 1st row. -
In stripe checkout page display Country or region fields how to remove it
image I am used stripe payment getaway for payment, In stripe checkout page display Country or region field and some country select then Postal code field appear both fields are required so how to remove this fields. Here is my code: checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": "order", }, "unit_amount_decimal": 5 * 100, }, "quantity": 1, }, ], customer_email="test@gmail.com", mode="payment", success_url=success_url, cancel_url=cancel_url, -
Pushing to Heroku Failed
I am trying to deploy my app to Heroku for the first time and I am running into the following error when trying to push using git: I've also tried git push heroku HEAD:main and git push heroku master with the same results. Is this a branch issue? What else could drive this? C:\Users\New User\Downloads\django-modal-ajax-crud-main\django-modal-ajax-crud-main>git push heroku main Enumerating objects: 185, done. Counting objects: 100% (185/185), done. Delta compression using up to 4 threads Compressing objects: 100% (169/169), done. Writing objects: 100% (185/185), 72.21 MiB | 1.29 MiB/s, done. Total 185 (delta 33), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime ("python-3.8.7") is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: ed5e29f5eae1f6c87fe608824165f38e3146d5af remote: ! remote: ! We have detected that you have triggered a … -
Django, webpack and NPM. Packaging seems to work, but can't access the code
Related questions appear not to be applicable in my case. As I do not understand where the issues lies, perhaps I am just not finding the solution. I have some experience with Django, but this is my first time working with webpack and NPM. My intended behavior is simple. I want to be able include the following JS code in my existing Django project and access/use scene. import * as THREE from 'three'; const scene = new THREE.Scene(); I have never worked with package (file?) managers, but I recognize that the import statement requires some kind of framework, like node or npm. I found a guide that explained how I could integrate Django with Webpack so I could make use of npm. Detailed code is below, but in short: I have a JavaScript file that contains the following code: console.log("Before import.."); import * as THREE from 'three'; const scene = new THREE.Scene(); console.log("After import.."); This file is located within my django static folder. In the Django .html that I am accessing I have included the following code {% load render_bundle from webpack_loader %} {% render_bundle 'main' 'js' 'DEFAULT' %} Here 'DEFAULT' refers to the following in myProject\settings.py: WEBPACK_LOADER = { … -
Django - Using Cast to query if CharField values are gte when not all values are string representations of ints
I have a DataField model in django that I use to store values for various field types. It looks like this: class DataField(models.Model): class FieldTypes(models.TextChoices): TEXT = 'Text', 'Text' QUANTITATIVE = 'Quantitative', 'Quantitative' SELECTION = 'Selection', 'Selection' name = models.CharField(max_length=50) field_type = models.CharField(max_length=150, choices=FieldTypes.choices) value = models.CharField(max_length=150) I want to be able to do a multi-query returning certain DataField types with certain values that are gte a given number, for example: DataField.objects.filter((Q("value__gte"= 1000) & Q(name= 'credit'))| (Q("value"= "Smith") & Q(name='Last Name'))) The problem is that the value field is a CharField, so I can't do gte filters. The field needs to be a CharField because I also store other word string values, like names. I've tried using Cast to create a value_int field for the query, but since not all values for DataField.value can be converted to an int I get a syntax error: queryset = DataField.objects.annotate( value_int=Cast('value', output_field=IntegerField()),).all() django.db.utils.DataError: invalid input syntax for type integer: "Smith" Is there a way I can add some logic to Cast so that if the value is not a valid integer it just goes to null? -
Relation with django
I have a question, I have 2 tables in my project (Customer, Machine) and I want to display the name of the customer in the MACHINE table. I have the relationship but I have not been able to create the Join. Could you help me validating this topic -
How do I import Chart.js Helper Functions in Django?
I am using chart.js with django and am receiving an error because I have not imported the chart.js helper functions getRelativePosition and getValueForPixel initialize:178 Uncaught TypeError: Cannot read properties of undefined (reading 'getValueForPixel') at tn.onClick (initialize:178:56) at tn.handleEvent (Chart.min.js:7:111837) at tn.eventHandler (Chart.min.js:7:111253) at n (Chart.min.js:7:110528) at HTMLCanvasElement.Se.<computed> (Chart.min.js:7:87040) The chart.js documentation says to import with the code below, but I don't believe this can be done in Django import { getRelativePosition } from 'chart.js/helpers'; https://www.chartjs.org/docs/master/getting-started/integration.html -
Python remove shapes from a pdf
In my setup, I have a student submit a pdf, and the teacher can annotate the pdf using the adobe embed api. This really nice since the teacher can create and delete comments. However, take the example case where a student writes their answers on a paper then scans them to a pdf. They then draw on the pdf with a pdf editor like Microsoft edge. after they submit and the teacher is editing, it is possible for the teacher to delete what the student has drawn because the embed API treats it as a shape. I don't want this to be possible. My backend is Django, so maybe there is some way for python to open a pdf file and "flatten" the shapes. Thanks