Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do a django multi-multi-selection form field
I have a django form where in a choice field the users can not only select more values but also select more combinations of values , for example: option1 option 2 and option 3 option 2 and option 4 here we have three combinations, the first one of one value (option1), the others of two values. How can I do that? Maybe I can use a M2M field with a through table where to associate at each option the combinations in which appear like this: option1: combination 1 option2: combination 2 and combination 3 option3: combination 2 option4: combination 3 I'm not sure the through table can have an undetermined number of combinations. Maybe there's a better way. Also any help on how to actually realize it will be appreciated because the widget allows only one combination. -
Parsing Complex JSON To Class (AttributeError: 'list' object has no attribute 'get')
(Sorry about the long but this is minimal to reproduce the error) I have been searching for the same error for a while but have not been able to find a solution. My aim is to parse the JSON data to classes so that it is easier for me to map it to a db schema and store the data in the database. I am using django and I am pretty new to learning it. Any guidance is very helpful My Attempt here. This link includes the JSON as well. ERR -> _CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = [CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalent.from_dict( y) for y in obj.get("CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents")] Entire code @dataclass class Period: instant: str startDate: str endDate: str @staticmethod def from_dict(obj: Any) -> 'Period': _instant = str(obj.get("instant")) _startDate = str(obj.get("startDate")) _endDate = str(obj.get("endDate")) return Period(_instant, _startDate, _endDate) @dataclass class Segment: dimension: str value: str @staticmethod def from_dict(obj: Any) -> 'Segment': _dimension = str(obj.get("dimension")) _value = str(obj.get("value")) return Segment(_dimension, _value) @dataclass class ShareBasedCompensation: decimals: str unitRef: str period: Period value: str @staticmethod def from_dict(obj: Any) -> 'ShareBasedCompensation': _decimals = str(obj.get("decimals")) _unitRef = str(obj.get("unitRef")) _period = Period.from_dict(obj.get("period")) _value = str(obj.get("value")) return ShareBasedCompensation(_decimals, _unitRef, _period, _value) @dataclass class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalent: decimals: str unitRef: str period: Period value: str @staticmethod def from_dict(obj: … -
Is there a way to check (from code) if django migrations haven't been executed yet?
with: ./manage.py showmigrations one sees the list of executed and pending migrations. I'd like to get this list (or number of migrations) at runtime so that I can expose it via a monitoring tool to see if any migrations failed. I checked the internals, but can't find any way to expose this for now. -
REST Framework applicability
There is Django, which allows you to create an application in the app of html pages. And there is an addition to Django - Django REST Framework, which allows you to implement the interface in the form of a REST API and receive JSON on GET, POST ... requests. So the question is, do I understand correctly that these two technologies are usually combined with each other in one application and the application is initially written in simple Django so that everything works, and then they supplement the Django REST Framework to add an additional interaction interface? I don't know anything about this topic, please help me. -
Problem with connecting Django, Celery, Redis to Azure Cache for Redis
I have an application where I am using django-celery-beats and django-celery-results libraries. I've configured everything and it works on my local machine but when I want to connect to Azure Cache for Redis then I get Error 11001 connecting to <app-name>.redis.cache.windows.net.redis.redis.cache.windows.net:6380. getaddrinfo failed.. I guess that it has something to do with CELERY_BROKER_URL and CELERY_RESULT_BACKEND in my settings.py file, however I can't find my mistake: This is what I have in my settings: CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "redis://redis:6379") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_RESULT_EXTENDED = True os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" my keys in my env file look like this: CELERY_BROKER=redis://<PRIMARY_KEY>@<HOST_NAME>:6379 CELERY_BACKEND=django-db What am I doing wrong in my settings? I want to use Redis for celery tasks like this one: @app.task(bind=True) def hello_world(self): print(f'Hello world!') -
Datepicker in Django and update tables with jquery or without
Good good evening! I've been thinking for a few days now and using different options to solve the problem - updating the table when a date interval is selected. I have a table and a form to display data and a calendar. I'm taking two different values from a calendar and trying to update the data in a table. But nothing happens to me. I would be very grateful if you manage to at least suggest something to find an error. Save me please. Maybe you will offer a more simplified version without using jquery - I will be very grateful. models from django.db import models class EmployeeModel(models.Model): empid = models.IntegerField(primary_key=True) empname = models.CharField(max_length=50) salary = models.IntegerField() joindate = models.DateField() class Meta: db_table = "employee" forms from datetime import date from django import forms from .models import * today = date.today() class StockHistorySearchForm(forms.ModelForm): start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) class Meta: model = EmployeeModel fields = ['start_date', 'end_date'] views from django.shortcuts import render from django_filters.views import FilterView from django_tables2 import SingleTableMixin # Create your views here. from django.http import HttpResponse from . import models from .models import EmployeeModel from .forms import StockHistorySearchForm def showresults(request): header = "HYSTORY DATA" queryset = … -
How to delete duplicate rows from a table using Django ORM?
I have a database table bad_reviews and a corresponding Django model BadReviews. I want to delete duplicate records based on the fields client_id, survey_id, text, rating, privacy_agreement. I've come up with this query which works: SELECT br.* FROM bad_reviews br JOIN ( SELECT client_id, survey_id, text, rating, privacy_agreement, COUNT(*) FROM bad_reviews GROUP BY client_id, survey_id, text, rating, privacy_agreement HAVING count(*) > 1 ) dupes ON br.client_id = dupes.client_id AND br.survey_id = dupes.survey_id AND br.text = dupes.text AND br.rating = dupes.rating AND br.privacy_agreement = dupes.privacy_agreement ORDER BY br.client_id, br.survey_id, br.text, br.rating, br.privacy_agreement, br.id How to rewrite it using Django ORM? -
sidebar django doesn't show
I created a sidebar in django where it shows some reports per user. I added a view to list the reports and show them in the sidebar, the thing is that it only shows in one page, and not in the other ones, I added the sidebar in base.html, so I don't know what to do. I'll add important functions views.py def insertar(request): usuario = Usuario.objects.get(username=request.session['username']) reportes = Reporte.objects.filter(id_usuario=usuario.id_usuario) return render(request, 'reporte.html', {'reportes': reportes}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('home', views.insertar, name='index'), path('home/<titulo>', views.reportes, name='reporte'), ] base.html <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> .sidenav { height: 100%; width: 250px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #21623a; overflow-x: hidden; padding-top: 20px; } .sidenav a { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 20px; color: #f1f1f1; display: block; } .sidenav a:hover { color: #818181; } .main { margin-left: 260px; /* Same as the width of the sidenav */ font-size: 25px; /* Increased text to enable scrolling */ padding: 0px 10px; } </style> <title>{% block title %} {% endblock %}</title> </head> <body> <div class="sidenav"> {% for i in reportes %} <a href="home/{{i.titulo}}" class="d-block text-light p-3">{{ i.titulo … -
Counting the number of hits in database using Django
Is it possible to count or return the number of hits, instead of the number of items in database table using Django queryset? For example, if the database table has a text column with two rows: 1, "Hi I am the first one. I am not the last one" 2, "Hi again. I am the second one." I want the result of Object.filter(text__regex=rf"one") to be three rows, not two because I have two "one" words in the first row. "Hi I am the first one. I am not the last one" "Hi I am the first one. I am not the last one" "Hi again. I am the second one." -
Struggling to point my form to a view with a variable in Django
Error: NoReverseMatch at / Reverse for 'language' with keyword arguments '{'name': ''}' not found. 1 pattern(s) tried: ['(?P[^/]+)/\Z'] I am creating a Encyclopedia app in Django which has a form as a input, which will display the search result from my view after searching those input variable in util.py file. I have created a form like below in my template <form method="get" formaction="{% url 'language' name=form.name%}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia </form> Here goes my urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>/", views.language, name="language"), ] And the language function in views.py(not writing whole views.py as it will take a lot of space here): def language(request, name): if util.get_entry(name): return render(request, "encyclopedia/entries.html",{ "entries": util.get_entry(name), "title": name.capitalize() }) else: return HttpResponseNotFound("<div style='text-align:center;font- family:sans-serif'><h1>Error</h1><h2> Requested page was not found.</h2></div>") -
Is it possible parse a model into a modelform?
If I had a person model and a person modelform, could I use the model to insert the values into the modelform and check if it is_valid? Example: class Person(models.Model: name = models.CharField(max_length=50) age = models.IntegerField(default=0) class PersonModelForm(ModelForm): model = Person fields = '__all__' if request.method == 'POST': name = request.POST['name'] age = request.POST['age'] person = Person(name=name, age=age) person_form = PersonModelForm(INSERT HERE SOMETHING) if person_form.is_valid: print('person_form is valid') -
Django persistent conection with mysql
Tried to set different value for CONN_MAX_AGE as described in documentation. I read about link and was trying to use this in my Django app. After setting this property i ran 10 concurrent requests using benchmarking tool (wrk)for a period of time. In MySQL I ran "show processlist" command it showed : show process list In the table Host and db entries are not changing for the period benchmarking is running, from which I am assuming that connections are being reused when setting CONN_MAX_AGE as non 0. While it was changing every moment when it was set as 0. After benchmark was completed I ran same request just once and it showed one more entry in show processlist with other previous values. But according to Django documentation it reuses the connection for time mentioned. Here although firing a new curl from terminal creating a new one. Can somebody help in understanding if there is incomplete documentation or lack in understanding? -
I have two models Flight and Airport. Airport is related to flight by foreign key. But while adding Flights into DB I am getting value error
from django.db import models # Create your models here. class Airport(models.Model): code = models.CharField(max_length=64) city = models.CharField(max_length=64) def __str__(self): return f"{self.id}:{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport,on_delete=models.CASCADE,related_name="departures") destination = models.ForeignKey(Airport,on_delete=models.CASCADE,related_name="arrivals") duration = models.IntegerField() def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" class Passenger(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) flights = models.ManyToManyField(Flight, blank = True,related_name="passengers") def __str__(self): return f"{self.first} {self.last}" When i query the objects in Airport i have both Newyork and london among the list of airports. But when i want add flights between them i am not able to do it. Its saying there is no instance called New York in the Aiport. I tried it with other Airports too and got the same error type In [5]: from flights.models import * In [6]: Airport.objects.all() Out[6]: <QuerySet [<Airport: 1:New York (JFK)>, <Airport: 2:London (LHR)>, <Airport: 3:Paris (CDG)>, <Airport: 4:Tokyo (NRT)>, <Airport: 5:Shanghai (PVG)>, <Airport: 6:Istanbul (IST)>, <Airport: 7:Moscow (Svo)>, <Airport: 8:Lima (LIM)>]> In [7]: f = Flight(origin = "New York" ,destination = "London" , duration = 818) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[7], line 1 ----> 1 f = Flight(origin = "New York" ,destination = "London" , duration = 818) File /opt/homebrew/lib/python3.10/site-packages/django/db/models/base.py:541, in Model.__init__(self, *args, **kwargs) … -
ModuleNotFoundError: No module named 'mongoengine.django'
I have been having a problem installing the dependencies from the social library. i have basically to install two dependencies, makemigrations, and migrate them normally. According to the docummentation, it states I have to run the two commands: pip install social-auth-app-django pip install social-auth-app-django-mongoengine And than add them to the INSTALLED_APPS in the settings.py file. Add in settings.py 'SOCIAL_AUTH_STORAGE = 'social_django_mongoengine.models.DjangoStorage'' Add in settings.py SOCIAL_AUTH_JSONFIELD_ENABLED = True than after all these five steps, makemigration and migrate. I'm executing the command 'docker compose exec web python manage.py makemigration` i'm also executing the command 'docker compose exec web python manage.py migrate' And the result is ALWAYS the same. ModuleNotFoundError: No module named 'mongoengine.django' The module is not being found! it is as i didn't put `'social_django_mongoengine' in the INSTALLED_APPS, which i certainly did. Tried to install diffrient versions, install it in docker container, and it didn't work. What to do? ` I have tried reinstalling the dependecies, rebuild docker containers, not it's not reading the module. Requirments.txt `asgiref==3.6.0 attrs==22.2.0 backports.zoneinfo==0.2.1 certifi==2022.12.7 cffi==1.15.1 charset-normalizer==2.1.1 cryptography==39.0.0 defusedxml==0.7.1 Django==4.1.4 dnspython==2.2.1 exceptiongroup==1.0.4 idna==3.4 iniconfig==1.1.1 oauthlib==3.2.2 packaging==22.0 pluggy==1.0.0 psycopg2-binary==2.9.5 pycparser==2.21 PyJWT==2.6.0 pymongo==4.3.3 pytest==7.2.0 pytest-django==4.5.2 python3-openid==3.2.0 requests==2.28.1 requests-oauthlib==1.3.1 six==1.16.0 social-auth-app-django==5.0.0 social-auth-app-django-mongoengine==1.0.0 social-auth-core==4.3.0 # social-auth-storage-mongoengine==1.0.0 sqlparse==0.4.3 tomli==2.0.1 urllib3==1.26.13 ` … -
rollup package splitting / code splitting
I am working on a components library (such as material-ui). I am using rollup for compiling. For the moment I can generate a single package, and to import a component such as a button, I can do it like that : import { Button } from "package-name"; Can I modify the rollup configuration to generate a separate package or chunk for each component. In other word, can I split the big-size package in separate small-size packages (one for each component) and use them in a way similar to this: import { Button } from "package-name/Button"; I start looking to the Code Splitting... But I am wandring if there is a known best practice to have this result? Is there a specific way to write the rollup.config file ? -
In Django, how can make an inline field editable only if it is null or empty?
I currently have a tabular inline that has an end_date field for a model. I want the field to only be editable if it is empty or null, and read only otherwise. Is there a way to achieve that? Currently, I have it editable regardless, but I want the data that already exists to be read only. Here is the code: class DeploymentInline(DecoratedTabularInline): model = Deployment readonly_fields = ['updated_at', 'updated_by', 'start_date', 'tool'] fields = ['tool', 'updated_at', 'updated_by', 'start_date', 'end_date', ] def has_add_permission(self, request, obj): return False I tried using get_readonly_field and checking the obj parameter, but it refers to the Project which is the admin.ModelAdmin the inline is in. -
New Angular poject in a devcontainer: Access Denied
I am developing in Visual Studio Code (Windows) using the .devcontainer. I am doing some testing using django and angular frameworks. Everything is working perfectly but when inside the container I run the command ng new angular-14-crud-example I have some problems: if after this I restart for any reason Visual Studio Code, the devcontainer does not restart anymore and returns the following error: failed to solve: error from sender: open C:\Users\user\project\angular-14-crud-example\node_modules\make-fetch-hap pen\node_modules\mkdirp: Access denied. Below are the details: Django_Dockerfile: FROM mcr.microsoft.com/devcontainers/anaconda:0-3 COPY environment.yml* .devcontainer/noop.txt /tmp/conda-tmp/ RUN if [ -f "/tmp/conda-tmp/environment.yml" ]; then umask 0002 && /opt/conda/bin/conda env update -n base -f /tmp/conda-tmp/environment.yml; fi \ && rm -rf /tmp/conda-tmp RUN pip install --upgrade pip RUN mkdir /workspace WORKDIR /workspace COPY requirements.txt /workspace/ RUN pip install -r requirements.txt COPY . /workspace/ docker-compose.yml version: '3.8' services: app: build: context: .. dockerfile: .devcontainer/Django_Dockerfile env_file: - .env volumes: - ../..:/workspaces:cached # Overrides default command so things don't shut down after the process ends. command: sleep infinity # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function. network_mode: service:db db: image: postgres:latest restart: unless-stopped volumes: - postgres-data:/var/lib/postgresql/data env_file: - .env volumes: postgres-data: devcontainer.json: { "name": "Anaconda (Python 3) & PostgreSQL", … -
How to create a subsection in django admin site of a model with some special filters?
I have a Law model and a custom command that amend Laws every 20 days. Now I want to email the admin that Laws are amended with a link redirecting to the admin site. In the admin section, I need a subsection of laws named LatestAmendedLaws that filters all the recently amended laws, so the admin can verify if laws are correctly amended. Here is the admin.py of Laws: @admin.register(Law) class LawAdmin(admin.ModelAdmin): list_display = ( 'id', 'rs_number', 'created' ) usually when a law is amended the created date updates. so we can filter with the created date. -
hi, I am using Django Framework I want to check if the mobile-no is in the database or not but I have error
I am using Django Framework I want to check if the mobile-no is in the database but I have error when I run the code it gives me only False even when the number is exist in database it gives me False can someone help me this is my code views.py @csrf_exempt def forget_password(request): mobile_no = request.POST.get('mobile_no') # verify = models.User.objects.all() # verify = models.User.objects.filter(mobile_no=mobile_no).first() verify = models.User.objects.filter(mobile_no=mobile_no).exists() if verify: return JsonResponse({'bool':True}) else: return JsonResponse({'bool':False,'msg' : 'mobile_no does not exist!!'}) -
i have one model which having foreign key with images feild and in that i have multiple images can i get them in single list like this :
Models.py class Cat_Breed_Detail(models.Model): id = models.AutoField(primary_key=True,verbose_name="id") key_name = models.CharField(max_length=35,default='',null=True,verbose_name="key_name") display_name= models.CharField(max_length=35,default='',null=True,verbose_name="display_name") def __str__(self): return self.key_name class Cat_Image(models.Model): image=models.ImageField(upload_to="ImagesCat/") cat=models.ForeignKey(Cat_Breed_Detail,on_delete=models.CASCADE,null=True,related_name='images') def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="150" height="150" />'.format(self.image.url)) else: return '(No image)' Selializer.py class CatImageSerializer(serializers.ModelSerializer): class Meta: model = Cat_Image fields = '__all__' class CatDataSerializer(serializers.ModelSerializer): class Meta: model = Cat_Breed_Detail fields = ['id','key_name','display_name','images'] response i am getting here i am getting nested response i dont want it i just want image url in images as a list not like the response i am currently getting : { "id": 9, "key_name": "abyssinian", "display_name": "Abyssinian", "image": [ { "id": 3, "image": "/media/Abyssinian_0006.jpg", "cat": 9 }, { "id": 4, "image": "/media/Abyssinian_0092.jpg", "cat": 9 } ] }, { "id": 18, "key_name": "american_bobtail", "display_name": "American Bobtail", "image": [ { "id": 5, "image": "/media/American_Bobtail_0004.jpg", "cat": 18 }, { "id": 6, "image": "/media/American_Bobtail_0057.png", "cat": 18 } ] }, { "id": 19, "key_name": "american_curl", "display_name": "American Curl", "image": [ { "id": 7, "image": "/media/American_Curl_0078.jpg", "cat": 19 }, { "id": 8, "image": "/media/American_Curl_0083.png", "cat": 19 } ] } i want to get all the images in one list not like image:{image:"...." ,image:"......"} i am new to djnago and still learning is there any way to make it done … -
Code is giving me an error: 'ManyToOneRel' object has no attribute 'related_model'
How can I retrieve a list of all foreign keys for a model in Django and access their corresponding models? I'm trying to loop through all the foreign keys for a model in Django and access the corresponding model for each foreign key. Here is my code: from django.db import models class MyModel(models.Model): # model fields for field in MyModel._meta.get_fields(): if isinstance(field, models.ForeignKey): related_model = field.related_model However, this code is giving me an error: 'ManyToOneRel' object has no attribute 'related_model'. How can I fix this and successfully retrieve a list of all foreign keys and their corresponding models for MyModel? -
check if the username in lowercase or uppercase now then get or create user if exist
check if the username in lowercase or uppercase now then get or create user if exist or firstly get or create then check if the username in lower or upper view.py def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'].lower(), email=form.cleaned_data['email']) user.set_password(form.cleaned_data['password']) user.save() if created: address = Address(label=form.cleaned_data['label'], city=form.cleaned_data['city'], area=form.cleaned_data['area'], long=form.cleaned_data['longitude'], lat=form.cleaned_data['latitude'], country=form.cleaned_data['country']) address.save() company = Company(owner=user, name=form.cleaned_data['name'], phone_number=form.cleaned_data['phone_number'], logo=form.cleaned_data['logo'], address=address, water_source=form.cleaned_data['water_source']) company.save() return super().form_valid(form) -
Django formset save() writes new object on database?
So I have MyModel: class MyModel(models.Model): name = models.CharField(_('Name'),max_length=80, unique=True) ... def save(self, *args, **kwargs): if MyModel.objects.count()>=5: raise ValidationError("Can not have more than 5 MyModels!") super().save(*args, **kwargs) # Call the "real" save() method. There are already 5 objects from MyModel on the database. I have a page where I can edit them all at the same time with a formset. When I change one or more of them, I will get the Validation Error "Can not have more than 5 MyModels!". Why is this happenning? I tought the formset was supposed to edit the existing objects, but it appears to be writing a new one and deleting the old one. What is really happening when I do a formset.save() on the database? Do I have to remove the save() method? -
Downloading dependent dropdown data in .txt file on clicking 'submit' button
I should be getting client and team as key value pair in data.txt when I hit the submit button but the file is blank. Any ideas/help/suggestions? -
How to move migrations files to outside of django project?
django-project/ migrations/ app1/ .../ src/ app1/ .../ config/ ... settings.py how to set the path in MIGRATION_MODULES in settings.py to make generated migration files appear in migrations/app1/ folder? I have tried MIGRATION_MODULES = {'contract': '..migrations.contract.db_migrations'} but got errors.