Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django Admin model page raise FieldDoesNotExist exception after a successful migration?
Scratching my head on this one. I've simply added a new field to a model. class Image(BaseModel): url = models.URLField(max_length=1000, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() # new field added below class Type(models.TextChoices): HEADER = 'HEADER', _('Header') type = models.CharField( max_length=20, choices=Type.choices, null=True, blank=True ) class Meta: db_table = 'Image' Then I ran python manage.py makemigrations followed by python manage.py migrate. This was successful and I can see the new field on the table in my database. The info from the django_migrations table looks correct. Here is my migration file: # Generated by Django 3.0.5 on 2022-03-23 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('example', '0082_auto_20220322_1937'), ] operations = [ migrations.AddField( model_name='image', name='type', field=models.CharField(blank=True, choices=[('HEADER', 'Header')], max_length=20, null=True), ), ] The problem I'm facing is when I visit that model page in the django admin, I get an internal server error with the following: Traceback (most recent call last): example_app | File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/utils.py", line 262, in lookup_field example_app | f = _get_non_gfk_field(opts, name) example_app | File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/utils.py", line 297, in _get_non_gfk_field example_app | raise FieldDoesNotExist() example_app | django.core.exceptions.FieldDoesNotExist example_app | example_app | During handling of the above exception, another exception … -
Redis is not Importing correctly in Django (with out Redis-cache configuration working perfectly)
Problem is that i'm not able to get the Redis-cache setting configuration right his is the Error im getting, Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() `File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs)_** File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\checks\caches.py", line 65, in check_file_based_cache_is_absolute cache = caches[alias] File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\core\cache__init_.py", line 52, in create_connection return backend_cls(location, params) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\cache.py", line 53, in __init__ self._client_cls = import_string(self._client_cls)_ File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import import_module(module_path) File "C:\Users\Ranajoy\AppData\Local\Programs\Python\Python310\lib\importlib__init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in call_with_frames_removed_ File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\client__init_.py", line 1, in ** from .default import DefaultClient File "C:\Users\Ranajoy\PycharmProjects\Recipe_App(Redis)\venv\lib\site-packages\django_redis\client\default.py", line 12, in from redis import … -
how to add the UPI or online payment feature in django project?
I am trying to create a website which has the online payment option like google pay, phone pay, paytm, netbanking and card. but I do not know how to do it. so, please tell me that how to do it, and give me an example code. thank you -
Python Post Form to external API
I need to get user form field in order to post to an external API, my question is how to pass form fields with Json payload. url = "" payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload) -
Make django application healthy on AWS instance
I am a beginner and I want to know how to find loose entry points in the pre existed application that can help to make aws server healthy. -
HOW TO EXTRACT THE FIRST FLOAT FROM A STRING IN DJANGO
I have a string containing a string and word, I want to extract the first float the string. myString = 12.5% per month myFloat= [float(s) for s in re.findall(r'\b\d+\b', myString )][0] I want to have 12.5 as myFloat. Thank you -
How to Kill all Celery background proces
Killing all celery processes involves 'grep'ing on 'ps' command and run kill command on all PID. Greping on ps command results in showing up self process info of grep command. In order to skip that PID, 'grep -v grep' command is piplined which executes 'not' condition on 'grep' search key. The 'awk' command is used to filter only 2nd and 'tr' command translates result of 'awk' command output from rows to columns. Piplining 'kill' command did not work and so the entire process has been set as command substitution, i.e., '$()'. The redirection at the end is not mandatory. Its only to supress the enitre output into background. kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1 -
Get and use the value from foreign key field without any conversions (Django)
I tried to get the value from the foreign key field "tax" in "priceWithTax()", then finally, I could get the value with this code below: taxObject = self.tax This is the full code: "models.py": from django.db import models from decimal import Decimal class Tax(models.Model): tax = models.DecimalField( max_digits=3, decimal_places=0, validators=[ MaxValueValidator(100), MinValueValidator(0) ], ) class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) TAX_ID = 1 tax = models.ForeignKey( Tax, on_delete=models.PROTECT, default=TAX_ID, ) @property def priceWithTax(self): # Here taxObject = self.tax tax = Decimal(str(self.tax)) return round(self.price * ((tax + 100) / 100), 2) But to use the value, I needed to convert it to "String" type first and then "Decimal type" next which became a little bit long code as shown below: taxObject = self.tax tax = Decimal(str(self.tax)) # Here So, are there any ways to use the value from the foreign key field "tax" in "priceWithTax()" without any conversions? -
needs to have a value for field "id" before this many-to-many relationship can be used
I have this error (needs to have a value for field "id" before this many-to-many relationship can be used.). I don't know how to fix it. I use Many-to-Many relationship for coauthor field which related with CustomUser. Also each coauthor have Profile. So I want that I can use coauthor by link in template to profile. Models.py class ArticleExample(models.Model): author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True ) coauthor = models.ManyToManyField( get_user_model(), blank=True, related_name="coauthor") title = models.CharField(max_length=150) text = models.CharField(max_length=150) views.py class ArticleExampleCreateView(CreateView): form_class = ArticleExampleForm model = ArticleExample template_name = 'example/articlecreateveiw.html' def form_valid(self, form): form.instance.author = self.request.user return super(ArticleExampleCreateView, self).form_valid(form) def post(self, request, * args, **kwargs): form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.author = self.request.user obj.save() form.save_m2m() return redirect('/') return self.render_to_response({'form': form}) Also it's my customuser and profile models class CustomUser(AbstractUser): date_birthday = models.DateTimeField( default=timezone.now, blank=True, null=True) class Profile(models.Model): slug = models.SlugField(unique=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) bio = models.TextField(null=False, blank=True) -
What is difference between Array and List in Python?
I'm new in Python. But I'm little confused about array and string. Some questions that i want to ask are. major difference which is best and why which one developers use mostly in projects. -
Celery tasks stopped running in Django app deployed using Heroku
We have a Django website deployed on Heroku (free plan) with a specific app for web crawlers that uses Celery and Redis. This app has celery tasks that add entries in our Postgres DB. Everything worked fine until a couple days ago when we updated some models and migrations from another unrelated app and suddenly all tasks stopped running (periodic tasks are registered, but don't run). The whole site is connected to Sentry and we didn't receive any error flags. We haven't changed anything in important files (such as settings, production config, requirements, tasks or procfile). Everything works fine locally. We have tried several things like excluding all registered tasks from the Django admin and putting them again. Testing different times. Rolling back to a few weeks ago, before our migrations, to see if the tasks ran... But nothing seems to work and we are feeling a little desperate since without the workers we are being forced to manually scrape several websites. We believe that the problem lies in the initalization of celery beat, and a log is provided here. Django admin: django admin for periodic tasks Procfile: release: python manage.py migrate web: newrelic-admin run-program gunicorn config.wsgi:application worker: newrelic-admin run-program … -
What fields can you call with request.user in Django?
Sorry for the dumb question but I can't figure it out. I have a class based view for a form. I like to make some changes if the request.user is equal with something. I used before in some other views request.user.profile.leader that gives me a boolean answer. Thats OK. Now in this class based view I like to use a very similar stuff but with another model like this: request.user.trust.group but it gives me nothing. What am I doing wrong? -
I'm unable to send emails from Django App on AWS
I'm unable to receive emails from my app after deploying to Aws, My app sits on Ec2 and I host my env on Elastic Bean, The emailing situation works fine locally but not on AWS. Note: I use Amazon SES I'm not sure on what to do next at this point, I don't seem to be able to find the problem. -
Using languages other than English for username in Django
I am working on a project a Django project in which a user may use local languages for their username. So in place of ISCIIUsernameValidator I used UnicodeUsernameValidator to solve this problem. But here I faced a problem. While testing I used three two languages Hindi and Japanese for username. Japanese: I used Katakana(アーロン), Hiragana(まつもと) and Kanji(田中) for the username and it worked. Nice Hindi: When I used simple words like 'कलम' it worked. But when I used complicated words like 'मोहित' or 'लेखक', it failed. And the error I received was Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters. This is the Account class from the models.py class Account(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=25, unique=True, validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) email = models.EmailField(_('email address'), max_length=30, unique=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) last_login = models.DateTimeField(_('last login'), auto_now=True) ref_code = models.CharField(_('Ref Code Used'), max_length=20, blank=True, null=True) is_active = models.BooleanField(_('active'), default=False, is_staff = models.BooleanField(_('staff status'), default=False) is_admin = models.BooleanField(_('admin status'), default=False) is_superuser = models.BooleanField(_('superuser status'), default=False) objects = AccountManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = _('Account') verbose_name_plural = … -
I've created objects in the admin page of my app, but I'm unable to call the object in my html template. I will put the views and the html lines below
from django.shortcuts import render, redirect from .models import * from .forms import * def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks': tasks, 'form': form} return render(request, 'todo_app/list.html') {% for task in tasks %} <div class="task-container"> <p>{{task}}</p> </div> {% endfor %} -
cannot use admin.modeladmin subclass
I've started django for 2 days and i get stuck in this section. i want change admin section but my class couldnt inherit from admin.modeladmin. when i want use list_display ,nothing load and python give me this error: <class 'django.contrib.auth.admin.GroupAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'title', which is not a callable, an attribute of 'GroupAdmin', or an attribute or method on 'auth.Group'. <class 'django.contrib.auth.admin.GroupAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'view', which is not a callable, an attribute of 'GroupAdmin', or an attribute or method on 'auth.Group'. from django.contrib import admin from .models import articles class articlesAdmin(admin.ModelAdmin): list_display=("title","view") admin.site.register(articles) -
Django docker migrations not working after renaming model
I have a Django Docker setup using postgresql in RDS. I managed to run the project successfully once and edited some model names. After that I built and launched a new container. I noticed that instead of getting the typical: "We have detected changes in your database. Did you renamed XXX to YYY?" I got all my models migrating for the first time and everything seemed to work until I got to the Django admin. ProgrammingError at /admin/upload/earnings/ relation "upload_earnings" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "upload_earnings" This is my Dockerfile. version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod nginx-proxy: container_name: nginx-proxy build: nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - ./.env.prod.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - acme:/etc/acme.sh depends_on: - nginx-proxy volumes: postgres_data: static_volume: media_volume: certs: html: vhost: acme: -
Django rest framework Serializer Save() problem
Hi there i am new ot django and django rest framework and i am having torouble when using serializers with PrimarayKeyTelatedFields() the code below is my code for my models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=50) age = models.IntegerField(default=0) class Book(models.Model): name = models.CharField(max_length=40) author = models.ForeignKey(to=Author, on_delete=models.CASCADE) below is my serializer code from rest_framework import serializers from books.models import Book, Author class BookSerializer(serializers.ModelSerializer): author_id = serializers.PrimaryKeyRelatedField(many=False, queryset=Author.objects.all()) class Meta: model = Book fields = ['id', 'name', 'author_id'] class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name', 'age'] and when i try to execute following commands in shell >>from books.api.serializers import BookSerializer, AuthorSerializer >> play1 = BookSerializer(data = { 'author_id':1 ,'name':'book1' }) >>play1.is_valid() True >>play1.save() After executing above i got the huge error as i pasted below Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in … -
How to send two response for a single post request in Django Rest Framework?
I am processing a video in backend but it's taking some time so I am looking for a way by which I can send the process time first and after it's completion I can send the video url. I tried using HttpResponse.write() but it didn't send the response. I got response only after the completion of whole process. -
PostgreSQL with Django failing to connect in Standar App Engine
I have a Django 4 app with PostgreSQL. I connected the SQL instance vie google-proxy correctly, however when I upload it into App Engine it fails to connect. settings.py if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloudsql/instancename', 'USER': 'user', 'PASSWORD': '********', 'NAME': 'database', 'PORT': '5432', } } else: DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", 'NAME': 'database', 'USER': 'user', 'PASSWORD': '******', 'HOST': '127.0.0.1', 'PORT': '5432', } } The error that on the screen was related with psycopg2: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/instancename/.s.PGSQL.5432"? /layers/google.python.pip/pip/lib/python3.9/site-packages/psycopg2/__init__.py, line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) I updated the requirements.txt because locally with the proxy everything was correct. asgiref==3.5.0 Django==4.0 django_better_admin_arrayfield==1.4.2 djangorestframework==3.13.1 django-cors-headers==3.7.0 django-filter==2.4.0 django-ratelimit==3.0.1 gunicorn==20.1.0 django-cors-headers==3.7.0 psycopg2==2.8.6 psycopg2-binary==2.9.3 pytz==2020.4 sqlparse==0.4.1 google-api-core==1.26.0 google-api-python-client==1.12.8 google-auth==1.27.0 google-auth-httplib2==0.0.4 google-cloud-core==1.6.0 google-cloud-storage==1.36.1 google-crc32c==1.1.2 google-resumable-media==1.2.0 googleapis-common-protos==1.53.0 I also added all the APIs necessaries according to the google docs Lastly, I read the logs in App Engine and the first error is about IAM rpc error: code = PermissionDenied desc = IAM … -
Django custom field change not detected by migrations
I have multiple custom fields in Django. First, they extended PositiveSmallIntegerField as we used int choices like: class BusinessLegalFormField(models.PositiveSmallIntegerField): choices = [(1,'SRO'), (2, ....] def __init__(self, *args, **kwargs): if not args or not args[0]: kwargs.setdefault('verbose_name', 'Právna forma') kwargs['choices'] = self.choices super().__init__(*args, **kwargs) Then I changed it to CharField and TextChoices: class BusinessLegalFormField(models.CharField): class Choices(models.TextChoices): ZIVNOST = 'zivnost', 'Živnosť' SRO = 'sro', 'Spoločnosť s ručením obmedzeným' AS = 'as', 'Akciová spoločnosť' def __init__(self, *args, **kwargs): if not args or not args[0]: kwargs.setdefault('verbose_name', 'Právna forma') kwargs.setdefault('max_length', 64) kwargs['choices'] = self.Choices.choices super().__init__(*args, **kwargs) The problem is that I just realized that Django didn't detect the type change. When I change something like null=True to null=False it is detected, but the DB type is not changed from number to char. How can I make it work? -
Configure IFC.js with webpack
I am running a django application and I want to use frontend stack for which I need a bundler. I am new to bundlers, but I decided to go with webpack and I am trying to configure IFC.js (https://ifcjs.github.io/info/docs/Hello%20world), following the hello world tutorial but using webpack. Right now I am running into the error: Field 'browser' doesn't contain a valid alias configuration but I am also unsure about the general configuration of my webpack. My config-file: const path = require("path") module.exports = { mode: "development", entry: { app: "/src/index.ifc.js" }, watch: true, devtool: "source-map", output: { filename: "[name].bundle.js", path: path.resolve(__dirname, "dist") }, module: { rules: [ { test: /\.ifc.js$/, exclude: /node_modules/, } ] }, resolve: { extensions: [ ".ifc.js" ] } I think what this means is that all files with the suffix .ifc.js will be compiled when running webpack. I can get it to work using a simple alert statement in the index.ifc.js file. It compiles it to the dist-directory and the JS-code executes. But when I copy the code from the hello-world tutorial I get: Field 'browser' doesn't contain a valid alias configuration /Users/myuser/projectfolder/myproject/myapp/static/node_modules/web-ifc-three/IFCLoader doesn't exist The code I am using copied from the tutorial: import { … -
Django how to Post Form to an Api [closed]
I need the user to fill a form with their information so that I can make a call to an external Api for customer compliance verification. Below is the example request import requests url = "https://spxon.getid.dev//api/v1/application/:id" payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload) print(response.text) How can I get user input for the form and pass into payload {} ? Thanks in advance -
Data don't automatically updated that I uploaded from django admin
In development , I uploaded some data from django admin to a table. But when I refresh a page that uses that table then the new added data don't appears . It appears only when i rerun the manage.py runserver command. How can i fix this? I am expecting that the new data from the table should appear after added through django-admin. -
Get a value before submitting a form in Django
class StudentRegistrationForm(forms.Form): end_year = forms.IntegerField(widget = forms.TextInput( attrs={ 'id': 'end-year' } )) grade_letter = forms.ChoiceField( choices= get_grades(get_year()) ) To get the list of grade_letters for choice I need to know the end_year value. How can I get the value of end_year field before the submit (when the user wants to choose grade_letter)?