Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ListSerializer and Foreign Key, is_valid doing N+1 query
I'm trying to improve my serializer to be able to create multiple objects with minimum queries. So I did implement a ListSerializer that will bulk create objects instead of calling save on each objects. Here my current code: class GatewayTechnicalLogListSerializer(serializers.ListSerializer): gateway = serializers.IntegerField(required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.gateways_ids: dict = {} for gat_tech_log in self.initial_data: self.gateways_ids[gat_tech_log['gateway']] = True self.gateways_ids = Gateway.objects.filter( id__in=self.gateways_ids.keys() ).only('id').values_list('id', flat=True) def validate(self, attrs): if attrs.gateway not in self.gateways_ids.keys(): raise serializers.ValidationError('Gateway does not exists.') return attrs def create(self, validated_data): gw_tech_logs_o = [GatewayTechnicalLog(**item) for item in validated_data] res = GatewayTechnicalLog.objects.bulk_create(gw_tech_logs_o) return res class GatewayTechnicalLogSerializer(serializers.ModelSerializer): class Meta: model = GatewayTechnicalLog fields = '__all__' list_serializer_class = GatewayTechnicalLogListSerializer My problem is now that when the method is_valid is called, it is trying to validate the foreign key gateway for each objects and so fetching the foreign key related. I'm trying then to remove the validation on that field and validating it myself but it doesn't change anything... I have not found any example of this, any ideas ? Thanks ! -
Using " ,".join in Django splitting every character, rather than item in list
I have a list of book genres I'm trying to display in in template using this code {% if title.my_books.genre.all %} <li class="list-group-item"> <kbd>Genres</kbd> {% for genre in title.my_books.genre.all %} {{genre.genre}}{% if not forloop.last %}, {% endif %} {% endfor %}</li> {% endif %} My goal is to display the items like so Autobiography, Biography, Memoir. And the above code DOES THAT. However, I've been asked to alter the code to use Django's join template tag detailed here https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#join Let's the say the items of the list are ['Autobiography', 'Biography', 'Memoir'] Obviously, if I don't have this line {% if not forloop.last %}, {% endif %} and just have {{genre.genre}} in the for loop, the values will display like Autobiography Biography Memoir However if I alter the above code like so following Django's docs: {% if title.my_books.genre.all %} <li class="list-group-item"> <kbd>Genres</kbd> {% for genre in title.my_books.genre.all %} {{ genre.genre|join:" ," }} {% endfor %}</li> {% endif %} The output on the template looks like this: A ,u ,t ,o ,b ,i ,o ,g ,r ,a ,p ,h ,y B ,i ,o ,g ,r ,a ,p ,h ,y M ,e ,m ,o ,i ,r How can I properly display the values … -
Django rerun signal as created
I've a signal running when some model DiseaseCase is saved: @receiver(post_save, sender=DiseaseCase) def add_or_edit_map_feature(sender, instance, created, **kwargs): ... if created: do_something() If I update some fields of one Instance of DiseaseCase Model using Django Shell or Django Admin do_something() will not run as the instance is edited but not created. Is there some way to edit the Instance but force created to be true to rerun the code? -
Django many-to-many contstaints validation
I am trying to create a constraint that checks whether both two fields have falsy values. One of these fields is a boolean, and the other is a m2m as in below: class Test(models.Model): public = models.BooleanField(default=False) target_groups = models.ManyToManyField("TargetGroup", blank=True) class Meta: constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_check_public_or_target_groups", check=Q(public=False, target_groups__isnull=True) ) ] This gets me 'constraints' refers to a ManyToManyField 'target_groups', but ManyToManyFields are not permitted in 'constraints'. Is there anyway I can check that either public is True or target_groups is not empty when creating/ updating? I checked this and this. I tried for example validating on the save method as in the following: def save(self, *args, **kwargs): if self.public is False and not self.target_groups.exists(): raise ValidationError( {"public": _("Notification requires either setting public boolean to true, or providing target groups.")} ) return super().save(*args, **kwargs) But the condition for self.target_groups is always false which I think makes sense since the object is not added to the set yet, but how do I validate the passed in data from the request? I use DRF and I can already validate this on serializers, but admins can add this through Django admin as well, so I am trying to validate this on the … -
Unable to migrate django tenant schemas
I have started implementing Django Tenant Sachems, I have apps called account, user_account and myapp. account is my public app. user_account is for user model app which i have used in both public and tenant app which is in tenant app. i need a foreign key relation in user_account from my tenant app. when i do make migrations no issue, but when i do migrate_Schema it throws error that "**Django. db. utils. Programming Error** : relation "myapp_institution" does not exist". -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/blog/Blog%20comments/
blog app urls urlpatterns = [ path('', views.blog, name="blog"), path('postComment/', views.postComment, name="postComment"), path('<str:slug>/', views.blogPage, name="blogPage"), ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) project urls/ urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), ] home app urls/ urlpatterns = [ path('', views.index, name="index"), path('contact/', views.contact, name="contact"), path('about/', views.about, name="about"), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) blog.html/ <a href="blog/{{post.slug}}">{{post.title}}</a> after this url became http://127.0.0.1:8000/blog/blog/Blog%20comments/ blog.html(changed)/ <a href="/{{post.slug}}">{{post.title}}</a> and after this url became http://127.0.0.1:8000/Blog%20comments/ in both case page not found but from home page url became this and work http://127.0.0.1:8000/blog/Blog%20comments/ index.html/ <a href="blog/{{post.slug}}">{{post.title}}</a> blog/views.py/ def blog(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, "blog/blog.html", context) def blogPage(request, slug): post=Post.objects.filter(slug=slug).first() comments= BlogComment.objects.filter(post=post, parent=None) context={"post":post, 'comments': comments,} return render(request, "blog/blogPage.html", context) -
Pass from Javascript to Django a template URL with PK
I implemented Ajax Search with success and results are loaded in a table which is in a template file. My TH are static and I append each result in < tr > < td >... in a foreach loop. tableBody.innerHTML += ` <tr> <td>${item.sku}</th> <td>${item.etat}</td> <td ${item.nom}</td> <td>${item.sst1}</td> <td>${item.sst2}</td> <td>${item.sst3}</td> <td>${item.pua}</td> <td>${item.cau}</td> <td><a href="/facture/auto-product-details/${item.id}"> <button type="button" class="btn btn-sm btn-labeled btn- info"> <span style="color: #fff;" class="btn-label"><i class="fas fa-sign-in-alt"></i></span></a></td> </tr> `; My problem is I had (above) to "hardcode" my URL "auto-product-details" because when I try to respect Django template syntax like this : <td><a href="{% url 'auto-product-details' ${item.id} %}">... but the URL is transformed in /facture/%7B%%20url%20'auto-product-details'%2036%20%%7D I tried to build piece by piece my URL in JS, tried to replace the {item.id } after the creation of a base (var) url without PK ... no success. It seems the special characters are transformed in HTML. Is there a way to achieve what I want to do ? -
Django form doesn't display
I'm trying to develop a simple Django app of a contact form and a thank you page, but I can't get the actual form to display at /contact/contact; all I see is the submit button. I'm not using Django 'admin' at all; no database, either. I'm working on locolhost using python manage.py runserver Why does my form not display? Do I need a model of the form? This is the directory structure: /contact/contact/urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] from django.urls import include urlpatterns += [ path('contact/', include('contactform.urls')), ] from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) /contact/contactform/urls.py from django.urls import path from . import views app_name = 'contactform' urlpatterns = [ path('thanks/', views.thanks, name='thanks'), path('contact/', views.contact, name='contact'), ] /contact/contactform/views.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from contactform.forms import ContactForm from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST def thanks(request): return render(request, 'thanks.html', {}) def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form_data = form.cleaned_data msg = MIMEMultipart() msg['From'] = EMAIL_HOST_USER msg['To'] = EMAIL_HOST_USER msg['Subject'] = f'Personal site: {form_data["subject"]}' message = f'Name: {form_data["name"]}\n' … -
FormMixin can't access POST method in Django
I have Question and Comment model and i want when i open Question-s detailview, also be form where i can create Comment object. i use FormMixin and DetailView (also i try ModelFormMixin) but when i send post request i have this error 'super' object has no attribute 'post' i know that FormMixin has post method. this is code --> class QuestionDetail(FormMixin, DetailView): model = Question form_class = CommentForm context_object_name = "detail" queryset = Question.objects.all() success_url = "/" def get(self, request, *args, **kwargs): try: question = Question.objects.get(id=self.kwargs["pk"]) except ObjectDoesNotExist: return redirect("Profile:home") return super(QuestionDetail, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): print("POST method is working") return super(QuestionDetail, self).post(request, *args, **kwargs) {% extends "base.html" %} {% block content %} {% include "./navbar.html" %} <div class="relative " xmlns="http://www.w3.org/1999/html"> <div class=""> <div class="p-6 mb-12 w-7/12 bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <div class="mb-2 flex "> {% for a in detail.category.all %} <p class="mr-2 text-sm text-blue-500">#{{ a.name }}</p> {% endfor %} </div> <a href="#"> <h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">{{ detail.title }}</h5> </a> <p class="mb-4 font-normal text-gray-700 dark:text-gray-400">{{ detail.text }}</p> <a href="#" class="inline-flex items-center py-2 px-3 text-sm font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"> წაიკითხე მეტი <svg class="ml-2 -mr-1 … -
Django Model Migration while stored in Session causes 500 Errors
I have an instance in Django where I store a selected "Property" for a user in Django Sessions. This allows a user to login to the system and select said Property to filter use based on that Property. Property is a Model and I store it in the session using PickleSerializer via SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' The issue is that when I need to make migrations on my Property model, it somehow messes up the pickled session and attributes are skewed (i.e. date fields are swapped with text fields) so it causes 500 errors. The only way I have found to stop the errors is by manually getting into the Production DB and logging users out by clearing the session table, but that is a pain and not ideal for CI. Is there a way to fix this? -
How to always filter a model by field in Django
Is there a way to always filter a model automatically? For instance, I would like to always filter an Employee by the company field when an employee model looks as such: class Employee(models.Model): company = models.FK... I don't want to always have to manually define a filter in the view as I do not want to miss filters... Excuse the dumb question. It has been awhile since I used Django.. -
In Python I want to parse a date range from a string to get a date_from and date_to
Working in Django I have a date range submitted on a form like this: <input type="text" class="form-control vans-dates-form-input" id="formGroupExampleInput" placeholder="Example input" name="daterange" value="02/01/2022 - 02/15/2022" /> I am passing this to a view in Django and want to split out the from and to date so that I have a 'date_from' and 'date_to' that I can work with. This is my view: from datetime import datetime from django.shortcuts import render, get_object_or_404 from vans.models import Van def booking(request): """This view returns the booking form page""" return render(request, 'booking/booking.html') def add_to_cart(request, item_id): """Adds the van booking to the cart""" van = get_object_or_404(Van, pk=item_id) # This will return the date range as a string date_range_str = request.POST.get('daterange') # In order to work with it I need it as two dates, date_from and date_to return render(request, 'booking/cart.html') -
Django how to add next button for related Blog post?
I have an blog list page where I listed all of my blog. Now I want to implement next button in my blog details page for move on next element if any blog object have child object. Assume I have 10 blog post where 5 blog post related to "python tutorial" so in my blog details page I want to add next button for this five blog post. If any blog post don't have any related blog then there will be not next button. How to do that? here is my model: Class Blog(models.Model): blog_title = models.CharField(max_length=300, unique=True) views.py def BlogDetail(request, slug=None): template_name = 'blog/blog_details.html' blog = None if slug is not None: blog = get_object_or_404(Blog, slug=slug) else: blog = None ....others code -
Django/html issue with displaying/linking image
I'm making a site by using django. One of my models contains ImageField. Files are saved in main_dir/media/images. I'd like to display specific images in templates but I can't achieve it. Instead of photo, I can see only default image icon which mean ( i guess ) that image is not found settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models class Gallery(models.Model): name = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def __str__(self): return self.name class Photo(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, default=None, related_name='photos') name = models.CharField(max_length=200) description = models.TextField(blank=False) image = models.ImageField(blank=True, upload_to='images') views def gallery(request, pk): gallery_object = Gallery.objects.get(id=pk) context = {'gallery':gallery_object} return render(request, 'Gallery/gallery.html', context) html <!DOCTYPE html> {% extends 'base.html' %} {% block content %} <h1>Gallery: {{ gallery.name }}</h1> {% for photo in gallery.photos.all %} <img src="{{photo.image.url}}"> <a>{{photo.image.url}}</a> #it's here only to check if path is correct {% endfor %} <a href="{% url 'home' %}">Go back to home page</a> {% endblock content %} what should I change to display image correctly ? -
Using django-extensions to generate a model graph in PNG format using Windows 10 (without using Conda or Anaconda)
I am using django-extensions to generate a model graph for my Django application. Using the pydot option from the graph_models documentation works for .dot files: $ python manage.py graph_models -a -I Device,Vehicle -o my_project_subsystem.dot But creating PNG files breaks (probably because (Py)GraphViz) cannot be installed correctly due to a missing header file. So this breaks: $ python manage.py graph_models --pydot -a -g -o my_project_visualized.png with an error: FileNotFoundError: [WinError 2] "dot" not found in path A fix to this problem using conda is provided in this answer. But how can I create graphs with only using pip without anaconda? Thanks in advance! -
Javascript function not triggering on click
{% extends 'base.html' %} {% block title %}Search{% endblock %} {% block content %} <script> I want this javascript to trigger when i click on the submit button. For some reason it runs the server side code not this javascript. When I click on the submit button it should technically trigger the javascript code but instead it runs the view function from the code behind document.getElementById('submit').addEventListener('click',function(){ search_input = document.getElementById("search"); if(search_input=="" || search_input==null){ alert("Enter something"); } }); </script> <div class="container-fluid"> <div class="row" style="margin-top:200px;"> <div class="col-md-6 mx-auto"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col"> <center>Enter username</center> </div> </div> <div class="row"> <div class="col"> <hr> </div> </div> <div class="row"> <div class="col"> <form id="search_form" name="search_form" action="{% url 'search' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Enter username" onclick="return test()"> </div> </div> </div> <br> <div class="row"> <div class="col"> <button type="submit" id="submit" class="btn btn-primary btn-lg" style="width:100%">Search</button> </form> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to access model from Foreign Key, Django?
I have 2 models in my project. What I want to do is access CustomUser model field "user_coins". But the problem is that I need to get it with only having offer_id from the TradeOffer model. So essentially what I would like to happen is to find the TradeOffer field with offer_id and through ForeignKey get the CustomUser field user_coins that the offer_id belongs to. I can't seem to figure out how to do that. class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=True, null=True) name = models.CharField(max_length=200, unique=True) user_coins = models.FloatField(default=0.00) class TradeOffers(models.Model): name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) offer_id = models.CharField(max_length=150, unique=True) offer_state = models.IntegerField() offer_message = models.TextField(null=True) trade_id = models.CharField(max_length=150, unique=True, null=True) date_added = models.DateTimeField(auto_now_add=True) -
Force blocking call for django in gevent worker of gunicorn
I have a django project run in gunicorn which has gevent as its thread class. Now for some parts of my program I need to call redis to get a key. This part runs inside an atomic block and must run as fast as possible. But when gevent monkey patch all libraries, it causes redis invoked non blocking and other greenlet starts processing which has very poor performance for me. How can I force redis or gevent to call this part blocking and get me the key without yielding the greenlet? I am using django 3.1 and gunicorn 20.0.4 with python redis client. -
Django - Retrieve or get data from selected foreign key field
Relatively new to Django, I'm working on a Django project and attempting to retrieve particular foreign key object into variable when it's selected in Form. model.py class item_category(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) def __str__(self): return self.nameCategory class item_code(models.Model): idItemCat = models.ForeignKey(item_category, on_delete=models.DO_NOTHING) idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) def __str__(self): return self.idItemCode I know I could retrieve object with making QuerySet such as .objects.last() and .objects.filter() or else, but it's just retrieve objects from database or existing data. What I'm about to do is, when a user submit a new data it'll retrieve particular foreign key object based on what I'm selected in this Form, so I could put into variable. Any idea how should do it? it would be so much appreciated. -
How can i check to see if a user is active using signals in django
Im trying to implement an online and offline functionality in my app in django and can't work out how to check to see if a user is logged in and active or offline and inactive in my app can anyone help me with implementing it please. -
Django: DB queries count optimization
I have models (one user can has multiple employees): from django.db import models class User(models.Model): username = ... first_name = ... last_name = ... class OrgUnit(models.Model): name = .... address = ... class Employee(models.Model): personnel_no = ... user = models.ForeignKey(User, related_name='employees'...) orgunit = models.ForeignKey(OrgUnit, ...) Serializers and views: class EmployeeSerializer(serializers.ModelSerializer): orgunit = serializers.CharField(source='orgunit.name') <==== one orgunit - one query to DB class Meta: model = Employee fields = '__all__' class CustomUserSerializer(serializers.ModelSerializer): employees = EmployeeSerializer(many=True) class Meta: model = User fields = '__all__' class UsersViewSet(ViewSet): def me(self, request): serializer = CustomUserSerializer(request.user) return Response(serializer.data) When serializing orgunit.name per one orgunit one query to DB is being performed. How to avoid this? How to prefetch employees related_name and its orgunits? -
django save method not changing attribute
Trying to use the save method to change the admin =True, on a user. But it is not changing. User models class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=55, null=True, blank=True) last_name = models.CharField(max_length=55, null=True, blank=True) phone_number = models.CharField(max_length=12, null=True, blank=True) delivery_info = models.ManyToManyField(Address, related_name='address_info', blank=True) is_active = models.BooleanField(default=True) verified = models.BooleanField(default=False) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser And my class where i want to change the admin class Employee(models.Model): """ Main class containing the employee """ user = models.OneToOneField(User, related_name='employee', on_delete=CASCADE) # Every employee have to have an ID, that is unique slug = models.SlugField(max_length=255, unique=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.email # Using slug to id the employee and be able to have its own # profile page to change information def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.user) super(Employee, self).save(*args, **kwargs) class Manager(models.Model): """ Holding the manager/admin employee """ manager = models.ForeignKey(Employee, related_name='manager', on_delete=CASCADE) def __str__(self): return self.manager.user.email def save(self, *args, **kwargs): if self.manager: self.manager.user.admin = True self.manager.user.staff = True super(Manager, self).save(*args, **kwargs) But when adding user as a manager, it does not change the admin fields to True. -
Warning: Unexpected input(s) ..., valid inputs are [...] in GitHub Actions (full text in the answer body)
After github action running I got this warning: Unexpected input(s) 'stack_file_name', valid inputs are ['entryPoint', 'args', 'host', 'port', 'passphrase', 'username', 'password', 'sync', 'use_insecure_cipher', 'cipher', 'timeout', 'command_timeout', 'key', 'key_path', 'fingerprint', 'proxy_host', 'proxy_port', 'proxy_username', 'proxy_password', 'proxy_passphrase', 'proxy_timeout', 'proxy_key', 'proxy_key_path', 'proxy_fingerprint', 'proxy_cipher', 'proxy_use_insecure_cipher', 'script', 'script_stop', 'envs', 'debug'] From main.yml: runs-on: ubuntu-latest needs: build_and_push_to_docker_hub steps: - name: executing remote ssh commands to deploy uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USER }} key: ${{ secrets.SSH_KEY }} passphrase: ${{ secrets.PASSPHRASE }} stack_file_name: docker-compose.yaml script: | sudo docker pull ${{ secrets.DOCKER_USERNAME }}/foodgram sudo docker-compose stop sudo docker-compose rm web touch .env echo DB_ENGINE=${{ secrets.DB_ENGINE }} >> .env echo DB_NAME=${{ secrets.DB_NAME }} >> .env echo POSTGRES_USER=${{ secrets.POSTGRES_USER }} >> .env echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env echo DB_HOST=${{ secrets.DB_HOST }} >> .env echo EMAIL_HOST=${{ secrets.EMAIL_HOST }} >> .env echo EMAIL_HOST_USER=${{ secrets.EMAIL_HOST_USER }} >> .env echo EMAIL_HOST_PASSWORD=${{ secrets.EMAIL_HOST_PASSWORD }} >> .env echo EMAIL_PORT=${{ secrets.EMAIL_PORT }} >> .env sudo docker-compose up -d sudo docker-compose exec -T web python3 manage.py makemigrations users --no-input sudo docker-compose exec -T web python3 manage.py makemigrations recipes --no-input sudo docker-compose exec -T web python3 manage.py migrate --no-input sudo docker-compose exec -T web python3 manage.py collectstatic --no-input sudo docker-compose restart sudo docker-compose exec -T … -
Best practice to show complex Json on the browser in javascript
I want to show the json object as tree like UI in browser. At first I try this [jqTree][1] However it requires that json will be this style { name: 'node1', children: [ { name: 'child1' }, { name: 'child2' } ] }, Without name childeren node , no tree appars. However my style is more complex and different node name. { title: 'node1', choices: [ { title: 'child1' , choices:[] }, { title: 'child2' choices:{ "answers":[1,2,4] } } ] }, Is there any good method to show more flexible json?? -
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError ... No module named 'django.core.urlresolvers'
The following error is happening when trying to deploy it using dokku. can any body tell me the reason, my environment is the following. python3.6 Django3.0 DRF3.11 Below is the log