Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a dependant drop-down in html form .using python
I want to create a dependant drop-down for my already existing drop-down in html form . Any one please recommend me a solution?? -
How to add two models in one page Django
When i try to add two models in one page it doesn't work and return the html code: How can i add to the one page two models? views.py def home(request): home_results = MainPageInfo.objects.all(); context_home = {'home_results': home_results} navigation_results_hone = Navigation.objects.all(); context_navigation_home = {'navigation_results_hone': navigation_results_hone} return render(request, 'index.html', context_home, context_navigation_home) models.py class Navigation(models.Model): title = models.FileField(upload_to='photos/%Y/%m/%d', blank = False, verbose_name=' SVG') class MainPageInfo(models.Model): title = models.CharField(max_length=255, verbose_name='Info') admin.py admin.site.register(Navigation) -
Getting data from MySQL table with 25+ columns using django model
I have a MySQL db (companies_data) with 4 tables (all_users, freq_user, special_users, products). all_users table has 27 columns and thousands of rows, I use that data to feed my machine learning algorithms. I'm using python, django rest_framework for backend. Now I wanted to get those data using django model and convert it into pandas dataframe so that I can predict and add the predictions to the other tables. Is there a easy way to get all the data using django model? Now I'm using raw SQL query with all the coloum names to get the data. -
Django permissions - how to prevent permissions_list from being sent to client
In my application, I found that all of the permissions list of all clients shown in page can be shown to the client. In the attached image, a user with role "assistant" can see the physician permissions. How can I prevent the permissions_list from being sent to client? -
Can Django's Replace be used to replace multiple substrings at once?
In Django, I can have queries that look like this: from django.db.models import Value from django.db.models.functions import Replace MyModel.objects.update(description=Replace("description", Value("old_1"), Value("new_1"))) MyModel.objects.update(description=Replace("description", Value("old_2"), Value("new_2"))) The first .update will go through the database, look for the "old_1" substring in the description field, and replace it with the "new_1" substring. The second .update call will do the same thing for the old_2 substring, replacing it with the new_2 substring. Can this be done in a single query? -
ManyToMany querying django
I have: Foo <=> FooGroup <=> Bar relation, where <=> stands for ManyToMany field. How do I retrieve all the Foos for a specific Bar instance? -
Django - How to set a value for Forms.HiddenInput() in Template
I currently have a form that has a field "id" that uses HiddenInput() as i do not want the user to fill in this input. I am trying to set this value "{{profile.id}}" for the "id" field inside the Django template but i cannot find anyway to do so. I have tried doing the following <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.value = {{profile.id}} }} ... <button type="submit">Submit</button> </form> and <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.initial = {{profile.id}} }} ... <button type="submit">Submit</button> </form> However, trying both of these does not work. If the "id" field is not a HiddenInput(), and just a regular TextInput(), i am able to set the value and the form is valid. Is there anyway to set a value for a HiddenInput() field? Here is my code: forms.py class CreateCommentForm(ModelForm): post = forms.CharField( widget=forms.HiddenInput() ) profile.html <form method="POST" enctype="multipart/form-data"> {%csrf_token%} {{form.id.initial = {{profile.id}} }} ... <button type="submit">Submit</button> </form> -
How to select multiple items in dropdown menu django?
I have django model: class at(models.Model): ... apostols = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='apostols', on_delete=models.CASCADE, null=True) ... Above and below apostols field are more fields which aren't important now. My form: class AtCreateForm(forms.ModelForm): ... class Meta: model = at fields = ['apostols'] widgets = { 'apostols': forms.widgets.TextInput(attrs={'class': 'form-control', 'list': 'user-list', 'autocomplete': 'off', 'multiple': True}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['apostols'].queryset = User.objects.all() In this form, we have apostols field which we display in template: <form method="post"> {% csrf_token %} <input type="text" list="user-list" multiple> <datalist id="user-list"> {% for user in form.apostols.field.queryset %} <option value="{{ user.username }}">{{ user.username }}</option> {% endfor %} </datalist> <input type="submit" value="Submit"> </form> This is how it works now. This form actually works as intented, but I want to be able to select multiple users. At best, it would work like on stackoverflow.com the tag-select section when you select more tags. -
Access list of field values for a list of related objects Django
I have a Django project where each Bid model object has a foreign key on an Event and a User along with some other information. The Event has a foreign key on a Post. I want to be able to test whether the current user is in the list of bids associated with an event using Django's frontend logic. I can use: {% for event in post.events.all %} {% for bid in event.bids.all %} {% if bid.bidder.pk == user.pk %} You have bidded on this event {% else %} You have not bidded on this event {% endif %} {% empty %} no bids on this event {% endfor %} {% endfor %} to test for this generally, but I only want one message to be printed for the user to see. I was hoping to do something more like: {% if user.pk in event.bids.all.bidder %} or (extending from the use of the for loop): ... {% if bid.bidder.pk == user.pk %} {% var bidded = True %} {% else %} {% var bidded = False %} ... I've heard of adding properties to my model for this sort of thing but I wanted to see if there was some … -
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.