Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement selection with pre-sorting in Django?
In the database, there is a table with two columns: 'City' and 'Post Office'. How to implement branch selection with pre-sorting by 'City'? I have absolutely no ideas, I would be grateful for any tips. -
I cant figure out how to add my "et" object to the group , i keep getting this error "'Group' object has no attribute 'et_set'
def etudiant_inscription(request): form = form_etudiant() if request.method == 'POST': form = form_etudiant(request.POST) if form.is_valid(): et = form.save() et.save() group = Group.objects.get(name="etudiant") group[0].et_set.add(et) return HttpResponseRedirect('/etudiant_login') else: return HttpResponseRedirect('/accueil') return render(request,'etudiant_inscription.html',{'form':form}) Traceback (most recent call last): File "C:\Users\Mega-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mega-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mega-PC\OneDrive\Desktop\testtttt\app\views.py", line 50, in etudiant_inscription group[0].et_set.add(et) Exception Type: AttributeError at /etudiant_inscription/ Exception Value: 'Group' object has no attribute 'et_set' """ what am i doing wrong exactly ? -
POST request returning 401 Unauthorised (only in Chrome)
I'm using Django Rest Framework and Vue.js to build a basic web app, and am currently working on the auth. Using axios to send a post request while registering a new user returns 401 in Chrome for some reason, but works in other browsers (Edge) and returns a 201 Created. The error in chrome is "detail: Invalid Token", but this particular endpoint (registration) doesn't even need auth/token to access. My frontend is at http://192.168.1.33:8080 and my backend is at http://127.0.0.1:8000 I am trying to POST data to http://127.0.0.1:8000/api/v1/users/auths/ The Network tab in chrome dev tools after trying a request: Request URL: http://127.0.0.1:8000/api/v1/users/auths/ Request Method: POST Status Code: 401 Unauthorized Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin Access-Control-Allow-Origin: http://192.168.1.33:8080 Allow: GET, POST, HEAD, OPTIONS Content-Length: 27 Content-Type: application/json Date: Mon, 06 Dec 2021 12:19:15 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.5 Vary: Accept, Origin WWW-Authenticate: Token X-Content-Type-Options: nosniff X-Frame-Options: DENY Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization: Token acf8b9099de5eba413dea141ce2c06b6cfb03159 Connection: keep-alive Content-Length: 53 Content-Type: application/json Host: 127.0.0.1:8000 Origin: http://192.168.1.33:8080 Referer: http://192.168.1.33:8080/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) … -
Django serverless timeout in Django admin
My project is set up on AWS Lambda, when I try to open my model in the DjangoAdmin interface I get an timeout message.I know that timeouts are given after > 29 seconds of loadtime. but I don't fully understand why my model gives a timeout. I've tried optimizing everything I know/can with my knowledge on the django side so that opening this model on localhost takes around 5.34ms to load. The only thing that I can think of is that my table has too many rows (6.448.277) which will only grow in the future... could that be the problem here and is there any way I can fix this in the django admin? admin code: Queries on localhost: -
Is there a way to filter by an annotation field where the Count is 0?
Here is the example I am referring to: all_hats = Hats.objects.all() issues=[] issues_to_match = [issue.id for issue in issues] matching_issues_count = Count("issues", filter=Q(issues__id__in=issues_to_match)) qs = all_hats.annotate(matching_issues_count=matching_issues_count) qs.filter(matching_issues_count=0) So if in this case issues is an empty list, when you print qs.matching_issues_count you get 0. So when you qs.filter(matching_issues_count=0) you should get that result no? In reality you return an empty queryset. Furthermore, print(qs.filter(matching_issues_count=0).query) returns an EmptyResultSet ValidationError Any information on this or do I have to structure the query another way? Or add a condition for when issues is empty? Thanks. -
How can I query in Django to a table with multiple conditions?
I have a table with fields channel_id, message_id and status. Each row in this table represents a message from a channel. The status can be SENT, DELIVERED or SEEN. When a user sends a message, a row is added to this table with the status SENT. When a user reads that message, another row is added with the status SEEN. So, for one message, I have multiple rows. I want to retrieve the rows from this table which have not the SEEN status, so I am able to know which message is not read. Is there a way of doing that with only one query to the database? -
How to remove members of a Team Django Python
I have teams and I have members (players). The Team owner is inviting a player to his team by email. And player is accepting invitation to join team. After acceptation they become a member of a invitated team. Now what I want to do is to make it possible for player to leave the team and also give possibility for the team owner remove player from their team. Since I am new with Django I can't achieve it yet. I've tried to create delete_member.html and function delete_member in Views first for Team owner to remove Its member but I don't see anything in that page. What Am I doing wrong? Apps: Team app - Views from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from .models import Team, Invitation from .utilities import send_invitation, send_invitation_accepted @login_required def team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) invitations = team.invitations.filter(status=Invitation.INVITED) return render(request, 'team/team.html', {'team': team, 'invitations': invitations}) @login_required def activate_team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) userprofile = request.user.userprofile userprofile.active_team_id = team.id userprofile.save() messages.info(request, 'The team was activated') return redirect('team:team', team_id=team.id) @login_required def add(request): if request.method == 'POST': title = request.POST.get('title') if title: … -
Not getting refreshed value for Django Serializer
I have 2 models Model A Fields : a_id, a_name, common_name and Model B Fields : b_id, b_name, common_name and my Serializer is like below for Model B class ModelBSerializer: model_a_obj_list = model_a.objects.all().values(a_id a_name common_name) common_name_list = {} for model_a_obj in model_a_obj_list: common_name_list[model_a_obj['common_name']] = { a_name: model_a_obj['a_name'] a_id: model_a_obj['a_id'] } a_model_details = fields.SerializerMethodField(read_only=True) def get_a_model_details(self, instance): return self.common_name_list.get(instance.common_name) class Meta(BaseObjectSerializer.Meta): model = Model_b This Seems to be working fine for API as i am getting modela data in modelb serializer data /api for model b { b_id: bid b_name:bname common_name: cname { a_name: aname_1 a_id: aid_1 } } Problem is when i do an update on MODEL-A. and change value of parameter lets say a_name: aname_1 changed to aname_2 But this change is not reflecting in api when i am running again Can some one help me, What am i doing wrong here ?? -
Can't access object primary key after creation
I did some primary key changes in my Django project which resulted in cleaning the whole database. I tested basically the whole database and it works correctly besides one thing. When creating object and using new primary key shortly after to redirect to its page- I have an error. zam = Zamowienie.objects.create(zam_nr_zam=nr_zam) return redirect('details', zam_id=zam.zam_id) The zam_id field is my new primary key. I tried to call it by simple return redirect('details', zam_id=zam.pk) but the results are the same. Simplified model: class Zamowienie(models.Model): zam_id = models.IntegerField(unique=True, primary_key=True) zam_nr_zam = models.CharField(max_length=25, unique=True) When I try to access url of the object it works correctly (after creation) http://ip/details/1/ Exact error message: Exception Type: NoReverseMatch Exception Value: Reverse for 'details' with keyword arguments '{'zam_id': None}' not found. 1 pattern(s) tried: ['details/(?P<zam_id>[0-9]+)/$'] Any idea what my caused the issue? -
get() returned more than one Modules -- it returned 2! (REST API - Django)
I am stuck in this issue for almost 2 days. Here is the issue. My models are like this: class Modules(models.Model): module_name = models.CharField(max_length=50) module_duration = models.IntegerField() class_room = models.IntegerField() def __str__(self): return self.module_name class Students(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() grade = models.IntegerField() modules = models.ManyToManyField(Modules) def __str__(self): return self.name My views are here: class StudentsViewSet(viewsets.ModelViewSet): serializer_class = StudentsSerializer def get_queryset(self): student = Students.objects.all() return student def create(self,request,*args, **kwargs): data = request.data new_student = Students.objects.create(name=data["name"], age=data['age'], grade=data["grade"]) new_student.save() for module in data["modules"]: module_obj = Modules.objects.get(module_name=module["module_name"]) new_student.modules.add(module_obj) serializer = StudentsSerializer(new_student) return Response(serializer.data) class ModulesViewSet(viewsets.ModelViewSet): serializer_class = ModudesSerializer def get_queryset(self): module = Modules.objects.all() return module ``` When I POST: { "name": "steve", "age": 16, "grade": 10, "modules": [ { "module_name": "math" }, { "module_name": "physics" } ] } It says: MultipleObjectsReturned at /app_Five/student/ get() returned more than one Modules -- it returned 2! I understand get() only get one element. But I think in "for" loop above only one "module_name" exists for each loop. So each time the get() executes, only one result for it to get. Can anyone tell me what I did wrong there? -
obfuscate Django Project
Similar questions has been already asked: How would I package and sell a Django app? But no real answer was provided previously! I have developed a Django app and to satisfy constraint of a security checklist, I have to obfuscate the project, otherwise the project will not get the necessary permits to be used by my client. I don't really care if it's a wast of time or if a determined person is eventually able to break the code. All I'm looking for is a reliable way to obfuscate the project while it's still perfectly functional. I don't mind if it can be deobfuscate after 1 second. -
Django: Unable to implement SimpleJWT
I am working on implementing Simple JWT authentication in Django. I followed the documentation and everything worked fine on my local machine. Now when I was replicating the steps on the server, an error occurred. To give a background, some migration files were deleted earlier, and makemigrations command was giving errors since dependencies were non-existent. Now I went on to this step of rotating refresh tokens, unaware of the fact that some migration files are missing, and ran the migrate command. Now after running the migrate command, Django started throwing errors, but the two token tables (token_blacklist_blacklistedtoken, token_blacklist_outstandingtoken) it creates, were created (obviously with a missing column). Now the TokenObtainPairView API started working, but I thought it can fail since we have a missing table column. So I did the following steps to revert back to the previous version. uninstalled djangorestframework-simplejwt Restored the settings.py Deleted the two token tables from DB using drop table command Now, when I'm following the documentation, I am not able to create the token table again, as the migrate command is telling me there is nothing to migrate. Generally, the applied migrations are registered in django_migrations table, but the token tables migrations were not listed … -
How do I get a visible default value for a field based on two fields, one from the same model and one from another model, in Django?
Following are my two models: class SomeThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) class AnyThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) net_fee=models.DecimalField(max_digits=7, decimal_places=2, default="Something.total_fee-discount") I want the net fee to be visible to the user in real time as he is filling up the form. The field must calculate the net fee by subtracting discount in the same model from the total fee in the previous one. Is there any Django-way for achieving it? -
how to use filter in query twice in django
I am trying to filter some data using this query, get_members = PaymentDetails.objects.filter(participants_name=Participants.objects.filter(participants_name=Profile.objects.get(user=request.user))) but I am getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. My models looks like this class Committee(models.Model): committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE) committee_name = models.CharField(max_length=100) class Participants(models.Model): participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE) participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE) class PaymentDetails(models.Model): participants_name = models.ForeignKey(Participants, on_delete=models.CASCADE) participants_paid_status = models.BooleanField(default=False) participants_amount_paid = models.IntegerField() -
Django dynamic formset with Jquery Ui autocomplete
Hi there I am fairly new to django and need to add dynamic formsets with autocomplete functions for every from. I am not entirely sure what I am doing wrong i have tried a few approaches and this is my most recent! I have function called AutoproductComplete which receives the id of the current formset form input that i want to add the auto complete to. It doesnt work, no errors, not sure why. I also did it after the after method so assume the form has been added to the DOM?' 'html' <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="input-group" style="padding:5px;"> {{form.productName}} {{form.orderQuantity}} <div class="input-group-append"> <button class="btn btn-success add-form-row" style="margin:5px;">+</button> </div> </div> </div> {% endfor %} <br> <div class="row spacer"> <div class="col-12 offset-9"> <button type="submit" class="btn btn-block btn- dark">Create Order</button> </div> </div> </form> JavaScript ''' function AutoproductComplete(id){ const products = []; console.log("This is working") console.log(id) {% for instance in products %} products.push("{{instance.product_name}}") {% endfor %} $(id).autocomplete({ classes: {"ui-autocomplete-input": "highlight"}, source: products, minLength: 1, }); }; AutoproductComplete("id_form-0-productName" ) function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var id = "" var total = $('#id_' + prefix … -
Django templates _set.all two sub table
I have two tables I want to check if there is data or not! {% if user.children_set.all.groups_set.all.exists %} -
How do you handle a PATCH request from HTMX in Django?
I would like to send a PATCH request to my app but I'm not sure how to consume the request in Django. I am currently getting the following error. AttributeError: 'WSGIRequest' object has no attribute 'PATCH' The input field in the HTMX file looks like this (I also made sure to send the CSRF token): <input hx-patch="{% url 'my_update' myobj.id %}" hx-swap="none" /> This is the Django View class MyHtmxView(View): def patch(self, request, *args, **kwargs): form = MyForm(request.PATCH) if form.is_valid(): form.save() # return an okay status? 200? else: return HttpResponse(self.form_invalid(form)) Django is receiving the request, but isn't sure what to do with request.PATCH. I can see in the Django docs that there is a HttpRequest.GET and HttpRequest.POST but no HttpRequest.PATCH https://docs.djangoproject.com/en/3.2/ref/request-response/#httprequest-objects. What's the best way to handle the PATCH? -
How to display products in child loop related to products in main loop with django?
The main loop displays product Card (B, C, D...) related by brand (or category) of product A. In product card B, C, D... That is, a sub-loop, showing up to 3 products with the same (exact) model as product B, C, D... Is there a way to do that for the DetailView. I also want to apply that to the tags on the category page (ListView). With the code in the parent loop it works fine, however the code in the child loop it doesn't work properly. My codes are as below (code has been shortened): Models.py class Modelp(models.Model): name=models.CharField(max_length=100, blank=True, null=True,) slug = AutoSlugField(max_length=100, populate_from='name') class Meta: verbose_name_plural='Models' def __str__(self): return self.name class Product(models.Model): title = models.CharField( verbose_name=_("title"), help_text=_("Required"), max_length=200 ) slug = models.SlugField(max_length=200, unique=True) modelp=models.ForeignKey(Modelp, blank=True, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.RESTRICT) brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.CASCADE) store = models.ForeignKey(Store, null=True, blank=True, on_delete=models.CASCADE) popularity = models.IntegerField(verbose_name=_("Popularity"), default=0) class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def __str__(self): return self.title def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) views.py class ProductDetailView(DetailView): template_name = 'product_detail.html' model = Product def get_template_names(self): if self.request.htmx: return 'product/all_variations.html' return 'product_detail.html' def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context_related_brand = Product.objects.filter(brand=self.object.brand).exclude( slug=self.kwargs['slug'])[:6] context_related_modelp = … -
Acess context from request in Django
How can we access the context passed in template in method views? def method_A(request): context = {"name":"sample"} html_template = loader.get_template('some_template.html') return HttpResponse(html_template.render(context, request)) Template as <div> {{name}} <a href="method_B">Redirect</a> </div> def method_B(request): # Here how to get context which was present earlier context = {"second":"second"} html_template = loader.get_template('template_B.html') return HttpResponse(html_template.render(context, request)) How we can get context in method based views in django.? So that it can be used in another templates. -
Django API split data by unique ID
I am making Django API. I collected place and review data using crwaling program. I want to split review data by building name(unique key), but it seems all reviews are saved together and is spread to all URL. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) #building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): if self.slug: # edit if slugify(self.building_name, allow_unicode=True) != self.slug: self.slug = generate_unique_slug(BuildingData, self.building_name) else: # create self.slug = generate_unique_slug(BuildingData, self.building_name) super(BuildingData, self).save(*args, **kwargs) class ReviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] A part of crwaling program if __name__=='__main__': for item in building_dict: BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call']).save() #BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() for item … -
Django filters custom date format for DateFilter
Can we customize date format for DateFiler in django_filters. Right now DateFilter accepts yyyy-mm-dd. Can we change it to mm-dd-yyyy? -
How to reference a serializer in Djano
I have two serializers for both Product and Ingredient models, I want to use both relations in the frontend side. As products in Ingredient model (ingredient.products) and I want the same in Product model (product.ingredients), so how can I get it? This is my code, class IngredientSerializer(serializers.ModelSerializer): # products = serializers.SerializerMethodField() //this line doesn't work class Meta: model = Ingredient fields = '__all__' class ProductSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) class Meta: model = Product fields = '__all__' And the Ingredient modal, class Ingredient(models.Model): products = models.ManyToManyField('Product', related_name="ingredients", null=True) name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) -
Django session is not creating in browser of computer Seems like antivirus blocking to create session session is creating if turn off antivirus [closed]
Django session is not creating in the browser seems like session creation is blocking by antivirus .(Session is working fine with non protected Browser) What may be the route cause of the issue . do we need to follow any standard to create session with out any blockage by antivirus ? -
Filter distinct objects from ManyToMany within ManyToMany
I have following Models in my Django DRF app. class FilterValue(models.Model): code = models.Charfield(…) class ProductVariant(models.Model): filters = models.ManyToManyField("FilterValue", blank=True, …) class Product(models.Model): variants = models.ManyToManyField("ProductVariant", blank=True, …) category = models.ForeignKey("Category", blank=True) And I’m trying to define function on Category model which will return all objects of FilterValue attached to all ProductVariants of all Products that are assigned in the category. Since I’ll have loads of different ProductVarints I can’t get away with nested loops since it’d be really slow. I had multiple attempts to solve it. I can of course get all Products within a Category using: products = Product.objects.filter(category=self) But then I get stuck on the fact that I actually need to filter nested ManyToMany object since I need all ProductVariants of all Products in the QuerySet and then - in the another level I need all ManyToMany FilterValue objects of each ProductVariant. Thank you. -
Create model instance only if its user id field is equal to the logged-in user's id
In a django rest framework app, there's a TextViewSet. The Text object structure is as follows: { text: text_value, author: author_id } When creating a new Text instance, I want to check if the supplied author_id equals the currently logged-in user's id. I've read this question: When to use Serializer's create() and ModelViewset's perform_create(), but still can't decide whether to override Serializer's create(), ModelViewset's create() or perform_create() methods. What's the right method to override?