Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Not able to run django app with Apache server in Mac Ventura
I am new to django app development. I am trying to use apache server for my django app in Mac OS Ventura. For this I am using mod_wsgi module to make the integration between Apache server and django app. I followed the required steps to do the setup, by making changes in httpd.conf and httpd-vhost.conf file. After the setup, I started the apache server but in the app log I am getting below error - [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Failed to exec Python script file '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752524 2023] [wsgi:error] [pid 30317] [remote ::1:62168] mod_wsgi (pid=30317): Exception occurred processing WSGI script '/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py'. [Mon Jan 09 16:16:41.752667 2023] [wsgi:error] [pid 30317] [remote ::1:62168] Traceback (most recent call last): [Mon Jan 09 16:16:41.752707 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/Data-Refresh-Website/datarefresh/datarefresh/wsgi.py", line 12, in [Mon Jan 09 16:16:41.752719 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.core.wsgi import get_wsgi_application [Mon Jan 09 16:16:41.752731 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/init.py", line 1, in [Mon Jan 09 16:16:41.752740 2023] [wsgi:error] [pid 30317] [remote ::1:62168] from django.utils.version import get_version [Mon Jan 09 16:16:41.752751 2023] [wsgi:error] [pid 30317] [remote ::1:62168] File "/Users/yadavv2/PycharmProjects/ESE/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in [Mon Jan 09 16:16:41.752761 2023] … -
Django smart fiter transfers
I have a model Book and there are duplicated rows in that table. One of the duplicates was changed during duplicate operation. The differences between that rows are in two fields (special_id and state). E.g.: Name special_id state Idiot "0107" 1 Idiot "0106" 2 During filtering by state if i write Book.objects.filter(state=2), i'll get the books with value of state 2, So i want to exclude this book if there is the book with the same name and with the state 1 Is there any way to do this without for loop and looking by the name of every book in QuerySet? Now when quantity of books is not big the delay of for loop is not noticeable. But when they'll be enormous i think it's going to be really long delay. -
Have multiple fields from another model linked by a foreign key
I have multiple models : class Circuit(models.Model): name = models.CharField('Circuit', max_length=120) country = models.CharField('Pays', max_length=120, choices=country_choices) version = models.CharField('Version circuit', default='Grand-Prix', max_length=120, choices=circuit_version_choices) image = models.ImageField('Image noir/blanc', blank=True, upload_to='circuit_pics', default='circuit_pics/a2*1ùp6*ù.png') image_details = models.ImageField('Image détaillée', blank=True, upload_to='circuit_details', default='circuit_details/a2*1ùp6*ù.png') class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") A race event takes place in a circuit. This circuit can have multiple versions (the version field in the Circuit model gives "Version1", "Version2", as possible choices). How can I have this choice also in the Event model, so that, in the admin section, I also have the choice to pick the circuit version it will take place in. More generally, how do I add multiple fields in a model from another model linked with a foreign key ? -
Use a django template variable in django-crispy bootstrap AppendedText or PrependedText
I saw that a similar question was asked 10 years ago about buttons and that it was resolved. I was naive enough to think that maybe it was possible for other fields ^^ Have I missed something ? As said in the Title, I'm trying to use a django template variable {{ tetra }} in a Layout Fieldset AppendedText or PrependedText value, like this class AddObjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'Some Text as Legend', AppendedText('userref', {{tetra}} ), but it won't work :-( I also tried with HTML tag like : PrependedText('userref', HTML("""{{tetra}}""") ), but in this case I also obtain : <crispy_forms.layout.HTML object at 0x7fb1997f8c70> Can anyone enlighten me, direct me or confirm that this is not possible? -
What is the right way to write test cases in django?
Unittest or Bultin test.Testcases or pytest I have these options. I have a socialmedia project where there is so many apis. should I only test apis with request methods or should I test every single views, serializers etc. Right now i m doing with django test.Testcases -
How to show if users already enable two-factor-auth on Django admin
Is there a way to show user two-factor-auth status on Django admin user list? From the documentation, I only found this manage.py two_factor_status user, which only show user OTP status on terminal. -
Django: How can I get the child element ListView and DetailView in the same Template?
I have a model for Letter_box and Letter. I want to display the "list of received letters" and "contents of the selected Letter" on the detail page of each Letter_box, but I don't know how. I can display the contents of the Letter_box and the list of Letter, but it is difficult for the letter contents. What I want to do is similar to this question (DJANGO: How to access data from ListView and DetailView on the same template?). However, the effect of pk on letter_box raised questions. Can you help me? models.py class LetterBox(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField("title", max_length=100) created_at = models.DateTimeField("create_date", auto_now_add=True) class Letter(models.Model): name = models.CharField("name", max_length=100) contents = models.TextField("cotents") created_at = models.DateTimeField("create_date", auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) letter_box = models.ForeignKey(LetterBox, on_delete=models.CASCADE) views.py class LikeLetterBoxDetail(LoginRequiredMixin,generic.ListView): template_name = "like_letter_box_detail.html" paginate_by = 2 def get_queryset(self): return Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']).order_by("created_at") context['letterbox'] = get_object_or_404(LetterBox, pk=self.kwargs['pk']) return context class LikeLetterDetail(LoginRequiredMixin,generic.DetailView): model= Letter template_name = "like_letter_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["letter_list"] = Letter.objects.filter(letter_box_id=self.kwargs['pk']) return context