How to choose template in DetailView based on a field of the model shown?

Advertisements I have a model with a choice field: type = models.CharField(choices=TYPE_CHOICES, max_length=1, default=UNSET, db_index=True) Depending on the type I’d like to show a different template in the class based DetailView: class AlbumDetailView(DetailView): […] Currently I have set the template by setting: template_name = ‘bilddatenbank/album_detail.html’ But then it’s not possible to access the value of… Read More How to choose template in DetailView based on a field of the model shown?

django: request.POST is empty

Advertisements I have the following rest API endpoint: def post(request, *args, **kwargs): print(request.POST) short_description = request.POST.get("short_description", "") long_description = request.POST.get("long_description", "") # rest of the code goes here when I call response = client.post("/foo/bar/api/v1/error/1", {"short_description": "hello", "long_description": "world", format=’json’) it gives me <QueryDict: {}> so both short_description and long_description is empty strings. How can I… Read More django: request.POST is empty

How to redirect to pagination page in Django?

Advertisements I have view: def questions(request,id): if request.method==’GET’: if question.objects.findId(id) == None: raise Http404 ans=answer.objects.sortByTop(id) return render(request, ‘question_page.html’,{‘page_obj’:paginate(ans,request,2), ‘answers’:ans, ‘que’:question.objects.findId(id)} ) if request.method == ‘POST’: form = AnswerForm(data=request.POST) print(form.data) que = question.objects.findId(id) print(que) print(que.title) ans = answer( txt=form.data[‘anstxt’], authorId=Profile.objects.get(profile=request.user), questionId=que, id=answer.objects.getLastId()+1 ) ans.save() a=answer.objects.sortByTop(id) i=0 for c in a: if c==ans: break i=i+1 return redirect(‘questions’,… Read More How to redirect to pagination page in Django?

How to print actual number when using Aggregate(Max()) in a Django query

Advertisements I have the following query set: max_latitude = Model.objects.aggregate(Max(‘latitude’)) When I print it, it returns {‘latitude__max’: 51.6639002} and not 51.6639002. This is causing a problem when I want to add the latitudes together to calculate an average latitude. If I do print(max_latitude.latitude) (field of Model object) I get the following: error:’dict’ object has no… Read More How to print actual number when using Aggregate(Max()) in a Django query

csrf_exempt for class based views

Advertisements class ErrorReportView(View): def get(self, request, *args, **kwargs): return HttpResponse(‘Hello, World!’) @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return HttpResponse(‘Hello, World!’) I use Postman, but I get <p>CSRF verification failed. Request aborted.</p> Documentation: https://docs.djangoproject.com/en/4.1/topics/class-based-views/intro/#decorating-the-class Could you help me? >Solution : The csrf_exempt decorator should be applied to "dispatch" method. You can add the following decorator directly… Read More csrf_exempt for class based views

Django query __startswith is not case sensitive

Advertisements I have been testing user searching with sorted results and I found this strange behavior >>> User.objects.filter(username__istartswith="AbC") <QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]> >>> User.objects.filter(username__startswith="AbC") <QuerySet [<User: AbC>, <User: AbCuuu>, <User: abc>, <User: abcuuu>]> Shouldn’t __startswith only have 2 of those results? I need to actually search with case sensitivity, how… Read More Django query __startswith is not case sensitive

Error when using comment form on website: (1048, "Column 'comment_post_id' cannot be null")

Advertisements I’m trying to implement a comment section below each blog on my site. I’ve got the form rendering but when I try to post a comment I get the following error: (1048, "Column ‘comment_post_id’ cannot be null") I cannot see what I’m doing wrong, I’ve also followed a tutorial step by step, although it… Read More Error when using comment form on website: (1048, "Column 'comment_post_id' cannot be null")

Need help in Python Django for fetch the records from DB which will expire in 30 days

Advertisements I wrote an application where there is a requirment to display only those records which will expire is next 30 day. models.py class SarnarLogs(models.Model): request_type_choice = ( (‘NAR’, ‘NAR’), ) source = models.CharField(max_length=100) expiry_date = models.DateField() def __str__(self): return self.source Views.py @login_required(login_url=(‘/login’)) def expiry_requests(request): Thirty_day = end_date = datetime.now().date() + timedelta(days=30) posts = SarnarLogs.expiry_date.filter(expiry_date… Read More Need help in Python Django for fetch the records from DB which will expire in 30 days

Django – How to use delete() in ManyToMany relationships to only delete a single relationship

Advertisements I have a model Voucher that can be allocated to several users. I used a M2M relationship for it. I want, in the template, the possibility to delete the voucher allocated to the logged in user, and the logged in user only (not all relationships). The problem I have is that the current model… Read More Django – How to use delete() in ManyToMany relationships to only delete a single relationship