Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a Queryset to a formset Field Django
I have a field 'product' in a formset , i want to make a queryset on that field OrderFormSet = inlineformset_factory(Order, OrderItems,fields=('product','item_price','quantity'), extra=0, ) -
Django Templating Language objects comparison
I'm fairly new to Django. I have a database with Events. I want to display the name of the Organisation where org_id is the foreign key in the events model. My approach was to load in all the objects and then do some iterating through them but I get no output on the website. I feel like its got to do something with the templating language models.py class Organisation(models.Model): org_id=AutoSlugField(unique=True) name = models.CharField(max_length=200) email=models.EmailField(max_length = 250) class Event(models.Model): event_id = AutoSlugField(unique=True) name = models.CharField(max_length=100) date = models.DateField() event_category = models.CharField(max_length=50) duration= models.IntegerField() org_id = models.ForeignKey(Organisation,on_delete=models.CASCADE) maxparticipants= models.IntegerField() teacher_id=models.ForeignKey(User,on_delete=models.CASCADE) releveant snippet from event_details.html <h3>Hosting Body</h3> {% for org in orgs%} {%if org.org_id == event.org_id %} <p>{{org.name}}</p> {%endif%} {%endfor%} <h3>Date</h3> <p>{{event.date}}</p> views.py def event_details(request,pk): event=Event.objects.get(event_id=pk) orgs=Organisation.objects.all() context={'event':event,'orgs':orgs} return render(request,'event_details.html',context) -
How Do You Trigger HTMX Page Refresh After User Updates Any Part of The Page?
I have been working with HTMX and it's pretty cool compared to the dreaded formsets and Javascript. I have it working....My only issue is when the user updates the form anywhere...you have to manually refresh the page to reset the list of todos. My issue is identical to this one...https://stackoverflow.com/questions/66664407/dynamically-update-table-when-creating-new-enty-using-htmx but there is not resolution listed..... Here's a quick overview of my code... My view... def create_to_do(request): user = User.objects.get(id=request.user.id) to_dos = NewToDo.objects.filter(created_by=user) form = ToDoForm(request.POST or None) if request.method == "POST": if form.is_valid(): to_do = form.save(commit=False) to_do.created_by = user to_do.creation_date = timezone.now() to_do.save() return redirect("MyToDoList:detail-to-do", pk=to_do.id) else: return render(request, "partials/to_do_form.html", { "form":form }) context = { "form": form, "user": user, "to_dos": to_dos, } return render(request, "create_to_do.html", context) Partial detailview.... <button class="button35" hx-get="{% url 'MyToDoList:update-to-do' to_do.id %}" hx-swap="outerHTML"> Update </button> <button class="button34" hx-post="{% url 'MyToDoList:delete-to-do' to_do.id %}" hx-swap="outerHTML"> Delete </button> </div> Partial todo form.... <div hx-target="this" hx-swap="outerHTML" class=""> <form method="POST"> {% csrf_token %} {% if to_do %} <button class="button35" hx-post="{% url 'MyToDoList:update-to-do' to_do.id %}"> Save </button> <button class="button34" hx-get="{% url 'MyToDoList:detail-to-do' to_do.id %}"> Cancel </button> </div> {% else %} <button class="button35" hx-post="."> Save </button> </div> {% endif %} </form> </div> My main create form html.. <button class="button36" hx-get="{% url 'MyToDoList:create-to-do-form' … -
Combine rows on django queryset
I have a querset with attributes location, person and error I need to either create a new queryset or edit an existing one such that rows are "combined" based on a certain criteria This criteria is if the location and person are the same Once combined, I want to make the error value be true if any of the rows that are being combined had a true value In this case, Location Person Error L1 P1 false L1 P1 true L2 P2 false L2 P2 false Location Person Error L1 P1 true L2 P2 false -
how to check the null property of a charfield null=true before migration?
I am new to Django and I want to implement a solution to the following problem : I would like to check before any migrations if my new charfield model fields have the attribute null set to false. If not i do want to stop the migrations and trigger a warning to inform the developer about it. How could I achieve that ? -
Save nested objects to ManyToMany field with DRF
Model: class Thread(models.Model): """Thread model for messages.""" participants = models.ManyToManyField(to=User, verbose_name=_("Participants")) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("Updated")) I have this serializers: class UserSerializer(serializers.ModelSerializer): """Serialize User model to get data from ManyToMany field to use in Thread participants.""" class Meta: model = User fields = ("id", "email") class ThreadSerializer(serializers.ModelSerializer): """Serializer for create, get, edit, delete Thread.""" participants = UserSerializer(read_only=True, many=True) class Meta: model = Thread fields = ("id", "participants", "created_at", "updated_at") And views: class ThreadListCreate(generics.ListCreateAPIView): """ Get threads list with participants details. Creates a new thread with two participants. """ permission_classes = (AllowAny,) queryset = Thread.objects.all() serializer_class = ThreadSerializer I need to create new Thread with exactly two users in "participants", how do I can? Also, to assign new users to "participants" I need to type only "id", like code below: { "participants": [ {"id": 1}, {"id": 4} ] } Now as a result of POST code above I get this: { "id": 28, "participants": [], "created_at": "2022-02-16T18:22:17.524911Z", "updated_at": "2022-02-16T18:22:17.524911Z" } -
django not saving media files in production
I set up django project on ubuntu 18.04 and apache2 but there is a problem. Media files don't save. When I try to upload file using django-filer I get 500 internal server error(I wrote simple plugin with charfield and filefield - the same happens) independently from DEBUG=True/False setting. I uploaded few files using manage.py runserver and this works great - I can even use these files in production but an attempt to upload any new one cause error settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/mysite/public/media/' STATIC_URL = '/static/' STATIC_ROOT = '/mysite/public/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] apache configuration: alias /static /mysite/public/static <Directory /mysite/public/static> Require all granted </Directory> alias /media /mysite/public/media <Directory /mysite/public/media> Require all granted </Directory> <Directory /mysite/src/proj> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-home=/mysite/venv python-path=/mysite/src/ WSGIProcessGroup mysite WSGIScriptAlias / /mysite/src/proj/wsgi.py In conclusion: manage.py runserver works great. On production server I can manage files which were uploaded earlier but an attempt to upload a new one cause error 500. -
docxtemplater in Vue js error Failed to read responseText on android
I have created a frontend app with Vue js on the Quasar framework, it works very well on the browser. But when I run it on android by using Cardova it does not work properly when it loads an MS word file from a remote server to fill it with some data. For templating I am using docxtemplater. And I take the following error: Error: InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). In addition, I have used Django as a server. -
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)