Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if database is present and migrated in elasticbeanstalk?
I have been trying to troubleshoot 500 error, on a django REST framework + reactjs app. I think the migrate is not executing correctly. The db-migrate.config file: container_commands: 01_migrate: command: "source $PYTHONPATH/activate pipenv run python manage.py migrate" leader_only: true DB_SETTINGS: eventually I want to change this to RDS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } eb deploy is successful. I still run into the 500 error, on localmachine the same endpoint works perfectly. How can I check whether the DB on elastic beanstalk has the necessary migrations? Any other causes I should be looking into? TIA -
Cannot get Python code to catch psycopg2 and Django errors
I cannot get my code to catch these exceptions: import psycopg2 from psycopg2 import IntegrityError, errors from django.db.utils import IntegrityError as ie ... try: parent = Code.objects.get(arrow=parrow) except (Code.DoesNotExist, psycopg2.errors.ForeignKeyViolation, IntegrityError, ie): logging.warning(f"Parent '{parrow}' of {child} not yet in database.") waitroom.append((parrow, child)) ... psycopg2.errors.ForeignKeyViolation: insert or update on table "codeAT_code" violates foreign key constraint "codeAT_code_childof_id_78f76bc4_fk_codeAT_code_uniqid" DETAIL: Key (childof_id)=(c74d8ad6-f23e-4b63-860f-e80f54b7c4cc) is not present in table "codeAT_code". The above exception was the direct cause of the following exception: django.db.utils.IntegrityError: insert or update on table "codeAT_code" violates foreign key constraint "codeAT_code_childof_id_78f76bc4_fk_codeAT_code_uniqid" DETAIL: Key (childof_id)=(c74d8ad6-f23e-4b63-860f-e80f54b7c4cc) is not present in table "codeAT_code" ... In addition to nothing being caught, PyCharm does not recognize psycopg2's ForeignKeyViolation, saying it is an unresolved reference. I've tried stating it many different ways. Please advise. Thanks. -
Limit characters user can enter in input in django OR html?
I had various occasions where I wanted to but couldn’t limit characters user types in html input. For example what would I do if I would only want numbers and letters? No other like £-“<#>{[. And what would I do if I would want them to only enter uppercase letters? Thanks for help:) -
Django admin search_fields FieldError
couldn't find anywhere answer to my question, and I'm trying to solve it for almost 2h right now. I have 3 models. Let's say A, B and C: class A(models.Model): product = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): product = models.ForeignKey(C, on_delete=models.CASCADE) class C(models.Model): name = models.CharField(max_length=200) And I want to search in my django admin by C.name in A model. How can I make it work properly? Here is my admin class: @admin.register(A) class AAdmin(admin.ModelAdmin): search_fields = ["product__product__name"] Right now im getting error: Related Field got invalid lookup: icontains -
Django dynamic form field validation
I have a form that I can set the fields for dynamically, like so: class MyForm(forms.Form): field_mappings = { 'my_field': {'field_type': forms.CharField()} } def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) initial_items = kwargs.get('initial') if initial_items: for k, v in initial_items.items(): field_mapping = self.field_mappings.get(k) if field_mapping: field_name = k self.fields[field_name] = field_mapping['field_type'] self.fields[field_name].initial = v During the GET request, I initialise it by passing in the initial values: MyForm(initial={'my_field', 'abcdefg'}) But I'm stuck on how to validate the fields in the POST request. From the docs, I think I should subclass the clean() method, select the field from the field mapping (depending on the POST field), and call it's validate(), method / something like this: args = args[0] if args: for k, v in args.items(): field_mapping = self.field_mappings.get(k) if field_mapping: field = field_mapping['field'] field.validate(v) but then what? -
PayPal API PopUp closes immediately after clicking PayPal button (Sandbox)
I am trying to implement the PayPal API into my Django / Vue checkout system, but everytime i try to access checkout via the paypal checkout buttons, thepopup closes immediately and i get these errors: Error messages in developer tools Obviously it has something to do with the cart's items' attributes and i tried to adjust them accordingly, but i can't figure out how to fix it. My Code: <template> <div class="page-checkout"> <div class="columns is-multiline"> <div class="column is-12"> <h1 class="title">Kasse</h1> </div> <div class="column is-12 box"> <table class="table is-fullwidth"> <thead> <tr> <th>Artikel</th> <th>Preis</th> <th>Anzahl</th> <th>Gesamt</th> </tr> </thead> <!-- vue for loop for looping through items in cart and displaying them in a table --> <tbody> <tr v-for="item in cart.items" v-bind:key="item.product.id" > <td>{{ item.product.name }}</td> <td>{{ item.product.price }}€</td> <td>{{ item.quantity }}</td> <td>{{ getItemTotal(item).toFixed(2) }}€</td> </tr> </tbody> <tfoot> <tr style="font-weight: bolder; font-size: larger;"> <td colspan="2">Insgesamt</td> <td>{{ cartTotalLength }}</td> <td>{{ cartTotalPrice.toFixed(2) }}€</td> </tr> </tfoot> </table> </div> <!-- Fields for user information --> <div class="column is-12 box"> <h2 class="subtitle">Versanddetails</h2> <p class="has-text-grey mb-4">*Felder müssen ausgefüllt sein</p> <div class="columns is-multline"> <div class="column is-6"> <div class="field"> <label>*Vorname</label> <div class="control"> <input type="text" class="input" v-model="first_name"> </div> </div> <div class="field"> <label>*Nachname</label> <div class="control"> <input type="text" class="input" v-model="last_name"> </div> </div> <div class="field"> … -
using F expression to access a field from one to many relationship not using the queryset resulted from prefetch_related method
hey guys let's say I have these models class Object1: ..... class Object2: user = models.ForeignKey(User) rel = models.ForeignKey(Object1, related_name = 'objects') isCOmpleted = models.BooleanField() and I wanted to perform this query: Object1.objects.all().prefetch_related(Prefetch('objects', Object2.objects.filter(user = specific_user))).annotate(is_completed=F('objects__isCompleted')) and the user is only related to one object from the Object2, but I got duplicate objects in my query, and I know the reason is that I have two objects from Object2 in my database for two different users, but the problem is that F expression didn't look in my prefetched query using prefetch_query, I tried the exact same thing in the shell and it's giving me the results that I have expected but not in the view, so what's the problem here exactly any help would be really appreciated -
How to make a user authentication by react django and redux
I want to make a user authentication by react, Django (using Allauth) and redux and also have Jwt authentication. what is the best way to do it? -
Django Signals maximum recursion depth when updating model field
I am trying to update a status field via signals but get a max recursion error. Using django 4.1.1. models.py class Product(models.Model): # …. PRODUCT_STATUS = ( ('P', _('Preparation')), ('S', _('Sold')), ('T', _('Shipped')), ) status = models.CharField(max_length=1, null=True, choices=PRODUCT_STATUS, default='P') price_sold = models.DecimalField( _('Price Sold'), max_digits=10, decimal_places=2, blank=True, null=True) #… signals.py @receiver(post_save, sender=Product) def post_save_product_set_status_sold_if_price_sold(sender, instance, created, **kwargs): if instance.price_sold != None: instance.status = 'S' instance.save(update_fields=['status']) I get the following error when saving RecursionError at /admin/products/product/14/change/ maximum recursion depth exceeded while calling a Python object Can somebody help? -
Access other domain files through Django sites framework
I'm trying to change the stripe api keys on the three domains that are on a digital ocean droplet. The project is using the Django sites framework to host these three domains. Therefore when I change the key it works only for one domain and not for the others. Is there a certain way to apply the changes to the other domains? -
Import django model to python script
I want to import models to a python script (test.py) using this code from .models import Template print('good') but it gives me this error : from .models import Template ImportError: attempted relative import with no known parent package this is my root : ├── project │ ├── __init__.py │ ├── modules.py │ └── test.py Any help is highly appreciated -
Django Store date only or query with date only
My requirement is, every year the post should be found by user with a specific date range. in end_date and state_date So i want to store only date or i have to query by date only instead of year But i found no way to do that, coz, it is storing year too class Post(models.Model): title = models.CharField(max_length=255, null=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) I have tried to query like this: post = Post.objects.filter( start_date__gte='09-16', end_date__lte='10-01' ) but above solution doesnt work well, any have ideas how can i do it? storing date only except year or query by date only?, so that it works every year without any hassle -
Bind mounts in docker compose won't synchronize local changes into container automatically on Mac M1
So I was working on a Macbook (with intel chip) and used the django-cookie-cutter template to start my project. Everything was working fine there. I then switched to a new mac with apple chip. Now my changes on host machine are not replicated in the docker container i.e the container is not restarted automatically. In my docker file, I have a 'docs' container which does restart on changes, but for the django container, I have to stop it manually with cmd+c and then restart it for my changes to take effect. Here's my local.yml (docker compose) file: version: '3' volumes: papersdb_local_postgres_data: {} papersdb_local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: papersdb_local_django container_name: papersdb_local_django platform: linux/x86_64 depends_on: - postgres volumes: - type: bind source: . target: /app working_dir: /app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: papersdb_production_postgres container_name: papersdb_local_postgres volumes: - papersdb_local_postgres_data:/var/lib/postgresql/data:Z - papersdb_local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres ports: - "5433:5432" docs: image: papersdb_local_docs container_name: papersdb_local_docs platform: linux/x86_64 build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./papersdb:/app/papersdb:z ports: - "9000:9000" command: /start-docs I also have another project with celery and celerybeat, both of them … -
Nginx returns standard pages and ignores Django urls
I've tried everything, and I don't understand what the problem is. OS: Ubuntu 20.04.5 LTS Nginx config: /etc/nginx/sites-available/default server { listen 80; server_name ***.**.***.***; charset utf-8; client_max_body_size 10M; location /static { alias /var/django-backend/static; } location /media { alias /var/django-backend/media; } location / { proxy_set_header Host $http_host; proxy_pass http://unix:/run/gunicorn.sock; } } P.S. Then I run the command sudo ln -sf /etc/nginx/sites-available/default /etc/nginx/sites-enabled Gunicorn service config: /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root WorkingDirectory=/var/django-backend ExecStart=/var/django-backend/venv/bin/gunicorn \ --access-logfile - \ -k uvicorn.workers.UvicornWorker \ --workers 3 \ --bind unix:/run/gunicorn.sock \ backend.asgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target When I go to any endpoint, nginx returns a 404 page -
user created with no password Django (users can't log in)
Im registering succesfully user, but when ot redirects me to login page I'm 100% sure password is correct, but it is not login me in, so I checked the admin page for that particular user, username exists, but it says that the password is not created yet. this is my views.py #from selectors import EpollSelector from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponseRedirect from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required # Create your views here def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f'You are now able to log in!') return redirect('login') else: form = UserRegisterForm() return render(request, 'Users/register.html', {'form': form}) @login_required def profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'You account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance = request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form' :u_form, 'p_form' :p_form } return render(request, 'Users/profile.html', context) and this is my forms.py code from socket import fromshare from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm from .models import Profile class UserRegisterForm(UserChangeForm): email = … -
Django - developing an app using a modular architecture
I made a learning management system using Django REST as its backend app. The app has grown quite a bit, so has its user base, and more and more people are showing interest in it. Something I have realized is that the state-of-art LMS applications have something in common: modularity--people can develop plug-ins, extensions, and easily add features. My app is monolithic and doesn't really allow that, so I'm considering reworking the code base to be more open to extension; especially, I'm trying to fit in a plug-in system. How would you approach something like that, in Django? Even some general thoughts, not necessarily Django- or Python-specific are very welcome. I'll give an example of a feature that would need to move from being hard-coded in the core to being something pluggable. Consider the following model: class Exercise(TimestampableModel, OrderableModel, LockableModel): """ An Exercise represents a question, coding problem, or other element that can appear inside of an exam. """ MULTIPLE_CHOICE = 1 OPEN_ANSWER = 2 CLOZE = 3 PROGRAMMING = 4 EXERCISE_TYPES = ( (MULTIPLE_CHOICE "Multiple choice"), (OPEN_ANSWER, "Open answer"), (CLOZE, "Cloze"), (PROGRAMMING, "Programming exercise"), ) course = models.ForeignKey( Course, on_delete=models.PROTECT, related_name="exercises", ) exercise_type = models.PositiveSmallIntegerField(choices=EXERCISE_TYPES) name = models.CharField(max_length=75, blank=True) … -
How can I make Django Username Field an instance in view
I am working on a Django Ticketing project where I want guest to activate Ticket PIN and then register for the event they bought the ticket for. And I want the guest user to have login access and update profile too. The issue is that I have a PIN Activation form page view and then followed by Guest Registration form which gives the guest access to providing Username and Password for login after a successful registration so they could update their profile. I am having two issues with my code as follows: I need the PIN value to be stored in the guest model so I would want to get the value of the PIN from the PIN Activation View unto the Guest Registration view (either by session but don't want PIN Form Field again as I did) and I also want to store the Guest Username from the Registration Form as an instance into the guest model as well. My reasons for storing the guest username and the PIN value into the guest model is to be able to get the Guest Profile, and PIN Details for Gate Pass. From my trial I am having the following errors: Cannot … -
Docker Windows - still rising RAM usage with django bulk_create()
I'm importing large amounts of data to django from csv. I created script with django-extensions which is creating objects like this: def process_row(row): return {"foo": row[0], "bar": row[1]} data = [] for row csv.reader(csvfile): if len(data) > 5000: MyModel.objects.bulk_create(data) data = [] data.append(process_row(row)) Basically, this works really good and fast, but the problem is still rising RAM usage by docker container. It never goes down. At the beggining container uses ~1.5GB, then after tens of bulk_create() it uses up to 10GB and I have to restart Docker Desktop to reset that. P.S. docker stats says it only uses ~3GB, so I think the problem is with Docker Desktop docker stats screenshot -
How can i select multiple tag from tag model in django
I'm beginner in Django/Python and I need to create a multiple select form. I know it's easy but I can't find any example. i use django-taggit.i want to select multiple tag in tag form. here is my forms.py class BlogPostForm(ModelForm): class Meta: model = BlogPost fields = ("title","body","tags") widgets ={ 'title' : TextInput(attrs={'class':'form-control ' ,'placeholder':'Title'}), 'body' : TextInput(attrs={'class':'form-control'}), } here is my models.py class BlogPost(models.Model): title = models.CharField( max_length=100,unique=True) body = RichTextField() date = models.DateTimeField(default=timezone.now) slug = models.SlugField() tags = TaggableManager() # class Meta: # verbose_name = ("BlogPost") # verbose_name_plural = ("BlogPosts") def __str__(self): return self.title -
"from django.shortcuts import render" gets me an error (red wavy line)
I have a decent amount of experience with Django, but recently I opened one of my old Django projects and realized there was something wrong with it. I looked through the files and I found that there were red wavy lines under: from django.shortcuts import render, from django.views import View, indicating that there is an error. I did not change anything I do not know what caused it. When I run the server I also get an error saying "name 'request' is not defined". Pleae help, here is the code: from django.shortcuts import render from django.views import View class Index(View): #creating different methods def get(self, requst, *args, **kwargs): return render(request, 'landing/index.html') -
How to return the values of functions called with yield in a ContextManager - Python
I am trying to organize my code by removing a lot of repetitive logic. I felt like this would be a great use case for a context manager. When making certain updates in the system, 4 things always happen - We lock the resource to prevent concurrent updates We wrap our logic in a database transaction We validate the data making sure the update is permissible After the function executes we add history rows to the database I want a wrapper to encapsulate this like below from contextlib import contextmanager @contextmanager def my_manager(resource_id): try: with lock(resource_id), transaction.atomic(): validate_data(resource_id) resources = yield create_history_objects(resources) except LockError: raise CustomError def update(resource_id): with my_manager(resource_id): _update(resource_id) def _update(resource_id): # do something return resource Everything works as expected except my ability to access resources in the contextmanager, which are None. The resources are returned from the function that's called during the yield statement. What is the proper way to access those resources through yield or maybe another utility? Thanks -
When using Generics types, how can I call an Attribute of an inherited class on the Base class instance with Python / Django?
Let's say I have a base Generic class called person to group all other persons that extend it: class Person(models.Model): name = models.CharField(...) And the class Worker, that extends the Person: class Worker(Person): card_id = models.CharField(...) When I access all Person objects I also see the Workers, but lets say that from there I want to do this: worker = Worker(name='Example', card_id='1234') person = Person.objects.all().first() Let's say that for some reason I want to use the Person class and call an Attribute o Worker: [in] person.card_id # Somehow expecting this result: [out] '1234 Is it possible, is it viable and how do I do it? -
How to write below sql query using Django queryset?
I have tried many solutions but could not find any luck, and also is django queryset faster than the raw sql join queries? Models - class S2BotCategoriesMappings(models.Model): id = models.IntegerField(primary_key=True) id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True) id_s2_bot_categories = models.ForeignKey(S2BotCategories, models.DO_NOTHING, db_column='id_s2_bot_categories', blank=True, null=True) class Meta: managed = False db_table = 's2_bot_categories_mappings' class S2UserSubscription(models.Model): id = models.IntegerField(primary_key=True) id_s2_users = models.ForeignKey('S2Users', models.DO_NOTHING, db_column='id_s2_users', blank=True, null=True) id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True) class Meta: managed = False db_table = 's2_user_subscription' query = """ SELECT s2_user_subscription.id_s2_users, s2_user_subscription.id_s2_bot, s2_bot_categories_mappings.id_s2_bot_categories FROM s2_user_subscription LEFT JOIN s2_bot_categories_mappings ON s2_user_subscription.id_s2_bot = s2_bot_categories_mappings.id_s2_bot; """ -
Dask task serialization in django
I am trying to set up prefect 2 with dask to run some tasks in django. One simple example with not much code runs fine but a larger example fails with: distributed.worker - ERROR - Could not deserialize task ****-****-****-**** Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2185, in execute function, args, kwargs = await self._maybe_deserialize_task(ts) File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2158, in _maybe_deserialize_task function, args, kwargs = _deserialize(*ts.run_spec) File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2835, in _deserialize kwargs = pickle.loads(kwargs) File "/usr/local/lib/python3.8/site-packages/distributed/protocol/pickle.py", line 73, in loads return pickle.loads(x) File "/tmp/tmpb11md_6wprefect/my_project/models/__init__.py", line 2, in <module> from my_project.models.my_model import * File "/tmp/tmpb11md_6wprefect/my_project/models/api_key.py", line 14, in <module> class ApiKey(models.Model): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The problem here is that I use an init.py in a model directory instead of using multiple apps etc. To circumvent this error in other places I did set up the django environment at the beginning of each task, e.g.: import datetime import xyz import django os.environ.setdefault( "DJANGO_SETTINGS_MODULE", os.environ.get("DJANGO_SETTINGS_MODULE", "core.settings"), ) django.setup() # No we import the models from my_project.models import MyModel This worked fine … -
Ajax returning None in Django views [closed]
I have here a data from an input, and I want to send it using ajax to my django views. But it's returning None. in my html <input type="text" id="title" name="chart-title" /> <input onClick="send()" type="submit" /> in my script. this is the onclick function function send() { data = {}; data.title = $("#title").val(); console.log(data); //working I can see the data $.ajax({ url: '{% url "save" %}', method: "POST", data: { id: `{{ id }}`, csrfmiddlewaretoken: "{{ csrf_token }}", chart_data: JSON.stringify(data), }, }) .done(function (response) { console.log(response);//also this is workin fine }) .fail(function (error) { if (error) notify(error); }); } in my views.py def saveChart(request): if request.method == 'POST': title = request.POST.get('title') print(title) //it's returning None here return JsonResponse({"msg": "bar"}, status=200)