Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is querying reverse foreign keys lazy?
I need to check if user has at least one connected product of many types that we have in a system. I'm trying to make it more efficient so I added any() and made a generator for connection check. But I wonder if it still will query all reverse relationships and evaluate them. User can have a lot of products of each type. My code: def has_connected_product(self): def check_product_set_on_connected(product_sets): for product_set in product_sets: if product_set.model.__name__ == 'ShopifyProduct': yield product_set.exclude(shopify_id__isnull=True).exclude(shopify_id=0).exists() else: yield product_set.exclude(source_id__isnull=True).exclude(source_id=0).exists() return any(check_product_set_on_connected([ self.user.shopifyproduct_set, self.user.commercehqproduct_set, self.user.wooproduct_set, self.user.ebayproduct_set, self.user.fbproduct_set, self.user.googleproduct_set, self.user.gearbubbleproduct_set, self.user.groovekartproduct_set, self.user.bigcommerceproduct_set, ])) -
Upload picture with ajax in django application
I am stuck on while trying to upload a picture with ajax on a django project. I have a series of button each of them activate a different modal. In that modal I should upload a picture and it gets loaded in the correct model. My post function is working but I'd like to do that without reloading the page. HTML (only the relevant part): <tbody> {% for question in questions %} <tr> <td>{{forloop.counter}}</td> <td>{{question.id}}</td> <td>{{question}}</td> <td> <a title="{% trans "Edit Question" %}" class="btn btn-warning btn-sm" href="{% url 'administration:edit_question' pk=question.id %}"><i class="fas fa-edit"></i></a> <a title="{% trans "See Details" %}" class="btn btn-primary btn-sm ms-3" href="{% url 'administration:question_details' pk=question.id %}" ><i class="fas fa-eye"></i></a> <a title="{% trans "Delete Question" %}" href="{% url 'administration:delete_question' pk=question.id %}" id="delete_question" class="btn btn-sm btn-danger ms-3"><i class="fas fa-trash"></i></a> <button title="{% trans "Add Image" %}" class="btn btn-sm btn-success ms-3" data-bs-toggle="modal" data-bs-target="#addImageModal{{question.id}}"><i class="fas fa-file-image"></i></button> {% if question.explanation %} <a title="{% trans "Edit Explanation" %}" href="{% url 'administration:edit_explanation' pk=question.explanation.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-edit"></i></a> <button title="{% trans "Add Explanation Image" %}" data-bs-toggle="modal" data-bs-target="#addExplanationImageModal{{question.id}}" data-questionId="{{question.id}}" class="btn btn-sm btn-secondary explanationModals ms-3"><i class="fas fa-plus"></i></button> {% else %} <a title="{% trans "Add Explanation" %}" href="{% url 'administration:add_explanation' pk=question.id %}" class="btn btn-sm btn-info ms-3"><i class="fas … -
Django return foreign key as object but use only uuid to create
I have 2 models, Subcategory and Quiz. Each quiz has one subcategory. I want to serialize the quiz to return the full subcategory object when I fetch it with get but be able to create a new quiz by passing in the uuid of the subcategory. If I use the SubcategorySerializer in the Quizserializer, I need to specify the full subcategory instead of passing just the uuid per POST. My Models: class SubCategory(BaseModel): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') description = models.CharField(max_length=100, blank=True, null=True) class Quiz(BaseModel): name = models.CharField(max_length=100) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name='subcategory') description = models.CharField(max_length=100, blank=True, null=True) My Serializers: class SubCategorySerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = SubCategory fields = [ 'uuid', 'name', 'description', 'category', ] class QuizSerializer(serializers.ModelSerializer): subcategory = SubCategorySerializer(read_only=True) class Meta: model = Quiz fields = [ 'uuid', 'name', 'subcategory', 'description', ] When I remove the subcategoryserializer from the model, I can use the uuid of an existing subcategory to create a quiz but then it also only returns the uuid when I fetch it. When I add it back, I get the right response when I fetch it but I can't use the uuid to create it -
How to use a Bootstrap Modal to delete in Django? help me plsss
or must add to JavaScript section or not if so help me i'm a newbie so please help me HTML </head> <body> <div class="container-xl"> <div class="table-responsive"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Shipping</b></h2> </div> <div class="col-sm-6"> <a href="add_ship" class="btn btn-success" ><i class="material-icons">&#xE147;</i> <span>Add New Shipping</span></a> <div class="col-sm-6"> <div class="search-box"> <div class="input-group"> <input type="text" id="search" class="form-control" placeholder="Search by Name"> <span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span> </div> </div> </div> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Destination</th> <th>Date</th> <th>Actions</th> </tr> </thead> <tbody> {% for shipping in shipping_info %} <tr> <td>{{ shipping.shipping_id }}</td> <td>{{ shipping.driver_id.driver_fname }} {{ shipping.driver_id.driver_lname }}</td> <td>{{ shipping.destination }}</td> <td>{{ shipping.ship_date }}</td> <td> <a href="{% url 'edit_shipping' shipping.shipping_id %}" class="edit" ><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> <a href="{% url 'view_shipping' shipping.shipping_id %}" class="" ><span class="material-icons"> visibility </span></a> </td> </tr> {% endfor %} </tbody> </table> i'm a newbie so please help me Help me plsss <form method="post" action=""> {% csrf_token %} <div id="deleteEmployeeModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <form> <div class="modal-header"> <h4 class="modal-title">Delete User</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p>Are you sure you want to delete these Records?</p> <p class="text-warning"><small>This action cannot be undone.</small></p> </div> <div class="modal-footer"> <input type="button" … -
use javascript to display django object
I want to implement below using javascript so row click it will get index and display object of this index. in django template this is working. {{ project.0.customer_name}} {{ project.1.customer_name}} but the below javascript are not working even I get the correct ID. var cell = row.getElementsByTagName("td")[0]; var id= parseInt(cell.innerHTML); document.getElementById('lblname').innerHTML = '{{ project.id.customer_name}}'; display django object using index in javascript. -
How can I get a total price column for CartItem model?
class Product(models.Model): name = models.CharField(max_length=80) product_image = models.ImageField(upload_to='product/product/images/%Y/%m/%d/', blank=True) price = models.IntegerField() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): item = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) qty = models.IntegerField(default=1) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) I'm trying to get an automatic total price that will be shown on check out page. I want to add a 'total_price' column on CartItem model and set the default 'item.price * qty', but when I tried to add this line to the class: total_price = models.IntegerField(default=item.price) since default value for qty is 1 but I got AttributeError: 'ForeignKey' object has no attribute 'price' error. I also tried add this to the class: @property def total_price(self): item = self.object.get(product=self.item) return self.item.price but I'm not sure which model will have the property? And when I added this method, I lost total_price column which I set its default as 0. I apologize for the lacking quality of solutions! -
Benefit of mod_wsgi daemon mode
I have written question django.urls.base.get_script_prefix returns incorrect prefix when executed by apache about the problems with providing urls for mezzanine pages (when executed by Apache the page urls were incorrectly formed). I just noticed that if I remove the mod_wsgi daemon mode from my Apache configuration the urls become correctly formed. Thus I'm asking what is the benefit of mod_wsgi doemon mode ? -
I am getting csrftoken in cookie and do not able to send in response make post, delete and put request from angular13 to Django rest framework
I need to make delete request to the server(django) from client(angular13) with session authentication, and i am also getting the session id and csrf token in the cookie but not able to make the request, i am getting csrftoken missing in the console. thank you //component.ts deleteStory(id : string){ console.log(id) this.storyapiService.deleteStory(id).subscribe(); } //service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { story } from './story'; import { Observable, of } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import {CookieService} from 'ngx-cookie-service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', cookieName: 'csrftoken', headerName: 'HTTP_X_CSRFTOKEN', // 'X-XSRF-TOKEN': 'csrftoken', }) }; @Injectable({ providedIn: 'root' }) export class StoryapiService { API_URL = 'http://127.0.0.1:8000/storyapi/'; constructor(private http: HttpClient) { } /** GET stories from the server */ Story(): Observable<story[]> { return this.http.get<story[]>(this.API_URL); } /** POST: add a new story to the server */ addStory(story : story[]): Observable<story[]>{ return this.http.post<story[]> (this.API_URL,story, httpOptions); //console.log(user); } /** DELETE: delete source to the server */ deleteStory(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id, httpOptions); } } //component.html <!--<h2>My stories</h2>--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="container mt-5"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." [(ngModel)]="filterTerm" /> </div> <ol> <li *ngFor="let story of … -
Django error: list index out of range (when there's no objects)
Everything works fine until I delete all the objects and try to trigger the url, then it gives me this traceback: list index out of range. I can't use get because there might be more than one object and using [0] with filter leads me to this error when there's no object present, any way around this? I'm trying to get the recently created object of the Ticket model (if created that is) and then perform the logic, so that if the customer doesn't have any tickets, nothing happens but if the customer does then the logic happens Models class Ticket(models.Model): date_posted = models.DateField(auto_now_add=True, blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) Views try: ticket = Ticket.objects.filter(customer=customer).order_by("-id")[0] now = datetime.now().date() set_date = ticket.date_posted check_time = now - set_date <= timedelta(hours=24) if check_time: print('working') else: print('not working') except Ticket.DoesNotExist: ticket = None context = {"check_time": check_time} -
How to add array of integer field in Django Rest Framework?
I want to add an array of integer fields in my model class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_the_week = ?? ( array of integer ) I tried with class Schedule(models.Model): name = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) day_of_the_week = models.CharField(max_length=100) and in the serializer add ListField class ScheduleSerializer(serializers.ModelSerializer): day_of_the_week = serializers.ListField() class Meta(): model = Schedule fields = "__all__" but this one is not working can anyone suggest me how to deal with this issue? -
can find the problem to solve Template doesn't working?
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'dashboard/home.html') from django.urls import path from . import views urlpatterns = [ path('', views.home), ] Plz Help me to Resolve the Problem adding path in template_DIRs -
Pointing Nginx to Gunicorn on a different server
I have a bunch of different services running across several lxc containers, including Django apps. What I want to do is install Nginx on the Host machine and proxy pass to the Gunicorn instance running in an lxc container. The idea is that custom domain names and certs are added on the Host and the containers remain unchanged for different installs. it works if I proxy_pass from the host to nginx running in a container, but I then have issues with csrf, which for the Django admin, cannot be turned off. Thus, what I would like to do is only run nginx on the host server connecting to the Gunicorn instance on the lxc container. Not sure if that will fix the csrf issues, but it does not seem right to run multiple nginx instances -
How to get filtered elements in table in paginator django
views.py get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) filtered_results = MyModelFilter(request.GET,queryset=get_records_by_date) context['filtered_results'] = filtered_results page_numbers = request.GET.get('page', 1) paginator = Paginator(filtered_results.qs, 5) users = paginator.get_page(page_numbers) context['users'] = users index.html <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> <th>start_time</th> <th>end_time</th> <th>scrapper_status</th> <th>processed_records</th> <th>new_records</th> <th>skipped_records</th> <th>error_records</th> </tr> </thead> <tbody> {% for stud in users %} {% csrf_token %} <tr> <td>{{stud.scrapper_id}}</td> <td>{{stud.scrapper_jobs_log_id}}</td> <td>{{stud.external_job_source_id}}</td> <td>{{stud.start_time}}</td> {% if stud.end_time == None %} <td style="color:red">No result</td> {% else %} <td>{{stud.end_time}}</td> {% endif %} {% if stud.scrapper_status == "1" %} <td>{{stud.scrapper_status}} --> Started</td> {% else %} <td>{{stud.scrapper_status}} --> Completed</td> {% endif %} <td>{{stud.processed_records}}</td> <td>{{stud.new_records}}</td> <td>{{stud.skipped_records}}</td> <td>{{stud.error_records}}</td> </tr> {% endfor %} </tbody> </table> <div class="paginator"> <span class="step-links"> {% if users.has_previous %} <a href="?page=1">&laquo; First</a> <a href="?page={{ users.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{users.page}} of {{users.paginator.num_pages}}. </span> {% if users.has_next %} <a href="?page={{ users.next_page_number }}">&raquo; Next</a> <a href="?page={{ users.paginator.num_pages }}">&raquo; Last</a> {% endif %} </span> I have to filter dates and need to find the status of checkbox the filtered element should show in table. Is there any solutions. How to paginate the datas based on the filtered result and pass the filtered results to the table. Is there any solution how to pass … -
How to convert a False or True boolean values inside nested python dictionary into javascript in Django template?
this is my views.py context = { "fas": fas_obj, } # TemplateResponse can only be rendered once return render(request, "project_structure.html", context) in the project_structure.html and javascript section const pp = {{ fas|safe }}; I get an error here. because fas contains a False or True boolean value somewhere deep inside. fas is complicated and has lists of dictionaries with nested dictionaries. What did work is I did this context = { "fas": fas_obj, # need a fas_json version for the javascript part # because of the boolean in python doesn't render well in javascript "fas_json": json.dumps(fas_obj), I know now I have two versions because I need the original version for the other part of the template in the javascript const pp = {{fas_json|safe}}; Is there an easier way than passing the original and the json version? -
I don't have django_redirect table with migration marked applied though
python manage.py showmigrations redirects [X] 0001_initial [X] 0002_alter_redirect_new_path_help_text Request URL: http://127.0.0.1:8000/admin/redirects/redirect/add/ But ERROR saying..... \Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_redirect -
I am getting csrftoken in cookie and do not able to send in response make post, delete and put request from angular13 to Django rest framework
I need to make delete request to the server(django) from client(angular13) with session authentication, and i am also getting the session id and csrf token in the cookie but not able to make the request, i am getting csrftoken missing in the console. thank you //component.ts deleteStory(id : string){ console.log(id) this.storyapiService.deleteStory(id).subscribe(); } //service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { story } from './story'; import { Observable, of } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import {CookieService} from 'ngx-cookie-service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', cookieName: 'csrftoken', headerName: 'HTTP_X_CSRFTOKEN', // 'X-XSRF-TOKEN': 'csrftoken', }) }; @Injectable({ providedIn: 'root' }) export class StoryapiService { API_URL = 'http://127.0.0.1:8000/storyapi/'; constructor(private http: HttpClient) { } /** GET stories from the server */ Story(): Observable<story[]> { return this.http.get<story[]>(this.API_URL); } /** POST: add a new story to the server */ addStory(story : story[]): Observable<story[]>{ return this.http.post<story[]> (this.API_URL,story, httpOptions); //console.log(user); } /** DELETE: delete source to the server */ deleteStory(id: string): Observable<number>{ return this.http.delete<number>(this.API_URL +id, httpOptions); } } //component.html <!--<h2>My stories</h2>--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="container mt-5"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." [(ngModel)]="filterTerm" /> </div> <ol> <li *ngFor="let story of … -
Django Rest Framework, how to use serializers.ListField with model and view?
I want to store an array of integers in the day_of_the_week field. for which I am using the following code models.py class Schedule(models.Model): name = models.CharField(max_length=100) day_of_the_week = models.CharField(max_length=100) serializers.py class ScheduleSerializer(serializers.ModelSerializer): day_of_the_week = serializers.ListField() class Meta(): model = Schedule fields = "__all__" Views.py # schedule list class ScheduleList(APIView): def get(self, request): scheduleData = Schedule.objects.all() serializer = GetScheduleSerializer(scheduleData, many=True) return Response(serializer.data) def post(self, request): serializer = ScheduleSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response("Schedule Added") Data save successfully but when I try to get data it returns data in this format "day_of_the_week": [ "[2", " 1]" ], is there any way to get an array of integers as a response? -
How can show variable in UI in django from view function?
I want to show value of pro in UI but not getting , here is my test view function code .value of pro is getting from previous function using django session variable. @api_view(['GET', 'POST']) def test(request): pro = request.session.get('j') print("Request ID from Index View : ", pro) if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data.get('myfield') print(selected) else: # rq = request_id["request_id"] s = sql() query = f"""update request_form_db.request_form_mymodel set is_approved=1 where request_id = '{pro}' """ print(query) s.update_query(query) print("Updated Successfully") form = TestForm() else: form = TestForm() context = {'form': form, 'pro': pro} return render(request, 'test.html', context) Here is my html code test.html <form action ="{% url 'test' %}" method="POST"> <div class="form_data"> {% csrf_token %} <br><br> {{form.myfield}} <label><b>Git Id</b></label> <br><br> <br><br> {{form.pro}} <input type="submit" value="Submit" class="btn btn-success" /> form.myfield returns what i want but value of pro variable not getting.please help -
Shengpay payment in Python (Django)
I need to set up customer payments using Shengpay. Is there any documentation or demo available for that. The official docs only support Java. I seatched the official docs and various search engines to see if anyone had implemented it before. Couldn't find anything. -
How to apply filtering over order by and distict in django orm?
Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Dane dddd@gmail.com 2017-06-04 Susan Susan@gmail.com 2017-05-21 Dane kkkk@gmail.com 2017-02-01 Susan sss@gmail.com 2017-05-20 I can get the first entries of each unique by using EmailModel.objects.all().order_by('date').distinct('Name'). this returns Name email date _________________________________________________ Dane dane@yahoo.com 2017-06-20 Kim kim@gmail.com 2017-06-10 Hong hong@gmail.com 2016-06-25 Susan Susan@gmail.com 2017-05-21 What i want to do here is to only include it in the result if the very first entry is something different like more filtering over it? for ex- i don't want to include it in the result if the first email id is dane@yahoo.com for Dave and only include it if it is something different. -
Show html spans for certain users only in Django
{% if show_approval %} <span>Approvals</span></a> {% endif %} I've to create this certain if condition in the html, where this Approvals would be visible for certain users, i've code for this in the python file context_data = {'show_approval': self.is_approval_supported()} I've to write a function to show it for this user only. where request.user == 'abcd@mail.com' i'm not sure how should i be writing this, i tried like this, but it ain't working. def is_approval_supported(request,self): if request.user == 'abcd@mail.com': return True else: return False -
django models Foreighn key правильно поставить
как поставить Foreighn key чтобы вибрать несколько объектов из выпадающий списка У меня два таблица один из них столбик выбираетса несколько вариант -
Serialize QuerySet to JSON with FK DJANGO
I want to send a JSON of a model of an intersection table so I only have foreign keys saved, I tried to make a list and then convert it to JSON but I only receive the ids and I need the content, I also tried in the back as a temporary solution to make a dictionary with the Queryset but the '<>' makes it mark an error in the JS, does anyone know a way to have the data of my foreign keys and make them a JSON? models: class Periodos(models.Model): anyo = models.IntegerField(default=2022) periodo = models.CharField(max_length=10) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) class Meta: app_label = 'modelos' verbose_name = u'periodo' verbose_name_plural = u'Periodos' ordering = ('id',) def __str__(self): return u'%s - %s' % (self.anyo,self.periodo) class Programas(models.Model): programa = models.CharField(max_length=255,blank=True, null=True) activo = models.BooleanField(default=True) class Meta: app_label = 'modelos' verbose_name = u'Programas' verbose_name_plural = u'Programas' def __str__(self) -> str: return self.programa class Programa_periodo(models.Model): periodo = models.ForeignKey(Periodos, related_name='Programa_periodo_periodo',on_delete=models.CASCADE) programa = models.ForeignKey(Programas, related_name='Programa_periodo_Programa',on_delete=models.CASCADE) class Meta: app_label = 'modelos' verbose_name = u'Programa Periodo' verbose_name_plural = u'Programa Periodo' def __str__(self) -> str: return self.programa.programa py where i send data def iniciativa(request): if request.user.is_authenticated: context = {} context['marcas'] = json.dumps(list(Marcas.objects.values())) context['eo'] = … -
Django template syntax: Compare with string fails
Here is the code: "parents" is a ManyToManyRelation key in model student. class Parents(models.Model): """docstring for parents""" name = models.CharField(_('name'),max_length=8, default="") phone_number = models.CharField(max_length=10) relationship_choices = [("M", _("mom")),("D",_("Dad"))] relationship = models.CharField(_("gender"),max_length=6, choices = relationship_choices, default="M"); Template: {% for parent in student.parents.all %} {% if parent.relationship =="M" %} <td name ="contactor"> {{parent.name}} </td> <td name ="relationship"> {{parent.relationship}} </td> <td name ="phone_number"> {{parent.phone_number}} </td> {% endif %} {% endfor %} This line {% if parent.relationship =="M" %} has error error: Could not parse the remainder: '=="M"' from '=="M"' What's the problem? Thanks. -
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct?
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct? currently i get all answers wrong, after the quiz.I Want, if the user choice the right answer, that he get a point and if the answer wrong than get he 0 points. views.py def math(request): if request.method == 'POST': print(request.POST) questions = QuesModel.objects.filter(kategorie__exact="mathematics") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'mathe.html', context) model.py class QuesModel(models.Model): Categorie= ( ("mathematics", "mathematics"), ("Business Administration", "Business Administration"), ) categorie= models.CharField(max_length=400, null=True, choices=Categorie) explaination= models.CharField(max_length=400, null=True) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) ans = models.CharField(max_length=200, null=True) def __str__(self): return self.question …