Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restrict .env file from apache
Let me first explain the requirement, I am hosting a Django project on centos and need to restrict .env from the URL. Sample URL :- https://example.com/.env I get 404 when accessing .env from the browser, but I need 403. When trying with debug enabled I get the below error details Page not found (404) Request Method: GET Request URL: http://example.com/403.shtml Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: ^sitemap\.xml$ ^admin/ ^blogs/ ^comments/ ^ckeditor/ ^list/$ [name='blog'] ^$ [name='recent-blogs'] ^all/$ [name='all'] ^media\/(?P<path>.*)$ The current path, 403.shtml, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Below is my apache configuration ProxyPassMatch ^/static ! ProxyPassMatch ^/media ! ProxyPassMatch ^/.well-known ! Alias /media /home/userdir/dir/dir/dir/media Alias /static /home/userdir/dir/dir/dir/assets Alias /.well-known /home/userdir/public_html/.well-known ProxyPreserveHost On ProxyPass / http://127.0.0.1:9173/ I tried some StackOverflow pages and other, but could not find an accurate solution. Can someone help me here? -
How to enforce uniqueness with NULL values
I have a model with a non-nullable CharField and 2 x nullable CharField: class MyModel(models.Model): name = models.CharField('Name', max_length=255, null=False) title = models.CharField('Title', max_length=255, blank=True) position = models.CharField('Position', max_length=255, blank=True) I want to ensure that name, title, and position are unique together, and so use a UniqueConstraint: def Meta: constraints = [ models.UniqueConstraint( fields=['name', 'title', 'position'], name="unique_name_title_position" ), ] However, if title is None then this constraint fails. Looking into why, this is because you can insert NULL values into columns with the UNIQUE constraint because NULL is the absence of a value, so it is never equal to other NULL values and not considered a duplicate value. This means that it's possible to insert rows that appear to be duplicates if one of the values is NULL. What's the correct way to strictly enforce this uniqueness in Django? -
Python: Django: How to run django app using a python script
I've a python file named "config.py" which actually checks the ip of user and run the django server on that port accordingly. The method I used there was to create a batch file using python and execute it later. import socket import subprocess x = socket.gethostbyname(socket.gethostname()) x = str(x) with open("run.bat", "w") as f: f.write(f'manage.py runserver {x}:0027') subprocess.call([r'run.bat']) But this method is not very effective. I want a way like: import something something.run("manage.py") or something accordingly Kindly Help me doing this -
Django isn't able to send emails but can login into my gmail acc
My Django app is able to log in into my Gmail account, but it is not sending emails. I know it logged in because I tried sending an email to a non-existing email-address and Gmail gave me this error. Even looked in my spam folders but nothing :( However, when I manually send an email, it works properly. This is my SMTP configuration in settings.py settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') I even tried hard-coding and changing the sender's email, but still no result. I wasn't getting this error a few days before, but for some reason it does seem to be working now. By the way, I'm using this for password reset functionality. -
Nginx Config for 2 django applications 2 different endpoints 1 server host
So the problem is I have 1 ip (127.0.0.1 for example) on my server lives 2 different django applications 1. /api 0.0.0.0:8000 2. /data 0.0.0.0:8090 3. / this will go to default pages served up by nodejs I need to figure out the nginx configuration of how to deploy these separate services, each with its own database. when navigating if an endpoint is hit, it will be routed to the appropriate app otherwise it will default to the nodejs app. extra info: when logging into /api/admin/ it gets routed to /admin and fails please take into consideration redirections made by django. I have tried a lot of things including setting Host, or Location This will be a bounty so happy hunting. -
How to use "Order" with prefetch_related to join other table values at once?
class Order(models.Model): user = models.ForeignKey(Account, on_delete=models.DO_NOTHING, related_name='orders') class Invoice(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='invoices') class Flight(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='flights') class Hotel(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='hotels') -
how to decode base64 data into image django - js
im trying to save captured image ( encoding data) into database from canvas , but it only saves a blank image ? here is my code const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const imgFormat = canvas.toDataURL(); docs.value = imgFormat const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} <input type="text" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" width=320 height=240></canvas> <button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button> </form> and here is my views.py with models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py import base64 from django.core.files.base import ContentFile @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': data = request.POST.get('documents') format, imgstr = data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) if data: photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj,'form':images}) i much appreciate your helps , please if you know something about it let me know … -
Factory boy RecursionError: maximum recursion depth exceeded
I have 2 models, django User model and Employee class Employee(TimeStampedModel): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="employees") first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) email = models.EmailField(validators=[email_regex], max_length=255, blank=True) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="employee") 2 factories: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User employee = factory.RelatedFactory( "control_room.tests.factories.EmployeeFactory", factory_related_name='user' ) first_name = fake.first_name() last_name = fake.last_name() username = factory.Sequence(lambda n: "user_%d" % n) email = fake.ascii_email() class EmployeeFactory(factory.django.DjangoModelFactory): class Meta: model = Employee creator = factory.SubFactory(UserFactory) first_name = fake.first_name() last_name = fake.last_name() phone = "+88005553535" email = fake.ascii_email() user = factory.SubFactory(UserFactory) so Employee model has 2 relations to User model (ForeignKey - creator and OneToOneField - user) when I create Factory boy models I get: RecursionError: maximum recursion depth exceeded How do I avoid this error? -
Save multiple objects with same unique value in Django
here's my problem. I have a view where I'm saving a formset of answers, I want it later to be possible to group those answers somehow. I have a couple ideas, for example I can make a model (AnswersGroup) and add a field to my Answer model, which would be foreignkey to AnswersGroup. Then I can create a new AnswersGroup instance in mentioned view and set Answer's AnswersGroup field to created object's pk, but I'm not sure if this is the best way to solve my problem. I also can add an IntegerField to my Answer model and calculate the next value for this field in my view, again, it looks too complicated. Maybe there's some kind of best practice for this kind of problem? -
Celery cannot connect to RabbitMQ server
I am trying to run celery and it is unable to connect to the RabbitMQ server even though I have correctly set the user, vhost and assigned the appropriate tags celery -A proj worker -l info The above command returns the error [2021-09-28 18:05:37,649: ERROR/MainProcess] consumer: Cannot connect to amqp://test:**@12:5672//: timed out. Trying again in 2.00 seconds... (1/100) I have initialized the celery app as follows app = Celery('proj', broker=f'amqp://test:test@12#4@localhost/test_vhost') I believe this is not working because the password test@12#4 has the special characters @ and # in it. How do I get this to work without changing the password. -
Django filter two records and update both at once?
I need to filter two data's and then update each data with different value ! How to do that at once ? x = Tasks.objects.filter(employee=[person1]) y = Tasks.objects.filter(employee=[person2]) Basically am updating count, for instance lets say i have a model named "Employee" and he is assigned to tasks with model named "Task". And whenever admin adds employees to a task - the employee gets to see the count of total task. With this said, i have managed to update the count by "1" when tasks gets added and managed to updated the count by "-1" when its get deleted, but my problem is when tasks gets updated or edited or assigned to another employee ! Now am updating the task using: x.update(total_task=F('total_task') + 1) and again y.update(total_task=F('total_task') - 1) From the above, first i filter each separately and then update separately ! How to combine this in a single query ? -
I am not able to submit the form and put the data in Database in a django website
I am fairly new to jquerry, infact just started learning and using it. I went through some of the questions but none talks about the issue I am facing so here it goes. I have created a website in django. In it i basically make a invoice and put that data into a sql server db and then fetch that data and render it to another html template and then print it from there. earlier i wasnt using a jquerry in the html. that time it worked all fine. now i decided that i will use the jquerry to append rows instead of having a fixed amount of rows. when i started using that it started giving trouble. now my input tag thats set on submit is not submitting the form, or thats what i think is happening. Can someone please help me out here. the following contains my part of the view which is working on this, the html and the urls file. views.py def invoice(request): if request.method == "POST": name_client = request.POST.get('client_name') address_client = request.POST.get('client_address') name_company = request.POST.get('company_name') address_company = request.POST.get('company_address') vessel_name = request.POST.get('vessel_name') po = request.POST.get('po') date = request.POST.get('date') item1 = request.POST.get('product1') cost1 = int(request.POST.get('cost1')) gst1 = … -
django debug toolbar uploaded badly
just starting using Django (first project) and I wanted to install the Django Debug Toolbar. I did exactly as the installation guide in the documentation here said: Django Debug Toolbar Docs- Installation For some reason the page loads like this: The html file that is loaded is a simple but legit one and ill add it here: <html> <body> {% if name %} <h1>Hello {{name}}</h1> {% else %} <h1>Hello World</h1> {% endif %} </body> BTW: Removing the if statements is not working either, also not working on both chrome and firefox. Thanks for the help :) -
Django image is uploaded to server but after showing 500 error without saving image information to db
In my settings `Debug = False Allowed_Host = ['my given host'] STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/images/" MEDIA_ROOT = os.path.join(BASE_DIR, "static/images") in Project Url urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in /etc/nginx/conf.d location /static/ { root /home/pijush/website/ecomerce; } location /images/ { # media files, uploaded by users client_max_body_size 100M; root /home/pijush/website/ecomerce; # ending slash is required } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; }` static files are serving perfectly. When Debug is True in localhost image is uploading and saving image info in model, working perfectly but in production after uploading image its showing 500 error. this is my gunicorn status log POST HTTP/1.0" 500 145 "https://nobann.com/profile/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" -
Why is unique=True not enforced when using create()?
I have a model with a unique charfield: class EmailTemplate(models.Model): name = models.CharField('Name', max_length=255, help_text=_("e.g: 'welcome_email'"), unique=True) When I create 2 models with the same name in Django's admin interface, I get the expected error: Email Template with this Name already exists.. However, if I do this programmatically I do not: >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > What am I missing? I thought unique was a db-level constraint? -
Get all values from queryset using templates
I am trying to retrieve all the queryset data (names and amount) using templates. views.py def get_expense(request): #expenses = list(Expense.objects.values()) expenses = Expense.objects.values('name' , 'amount') if request.method == 'POST': form = ExpenseForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() #print(driver_text) print(type(expenses)) return render(request, 'thanks.html', {'expenses':expenses}) #JsonResponse(expenses, safe=False) # else: form = ExpenseForm() return render(request, 'index.html',{'form':form}) thanks.html: {{ expenses }} I am trying to get all those queryset data listed but instead I am getting: <QuerySet [{'name': 'Home Rent', 'amount': 8000.0}, {'name': 'hjvhjvhv', 'amount': 73.0}, {'name': 'tes', 'amount': 23.0}, {'name': 'dddd', 'amount': 34.0}, {'name': 'qqqqqqqq', 'amount': 56.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'hjvhjvhv', 'amount': 67.0}, '...(remaining elements truncated)...']> I need only the name and amount listed instead of the whole queryset. -
ValueError: Cannot assign "'x'": "x.x" must be a "x" instance
I am trying to create some comments on a venue in my web app but I am mot sure why I am getting this error when I try and pass a venue's id through to make a new comment object models: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=15000) [...] class VenueComments(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=10000) views def add_venue_comment(request): if request.method == "POST": comment = request.POST.get('comment') venue = request.POST.get('venue_id') new_obj = VenueComments() new_obj.venue = venue new_obj.user = request.user new_obj.comment = comment new_obj.save() return JsonResponse([ new_obj.comment, new_obj.user ], safe=False) -
django api with custom user app authentication
I created a django project tha uses a customUser for authentication, following this blog post. I now would like to attach another app to the project that is a REST API that leverages that authentication. In this new app I create a model for the data that the uses will consume and I add as foreign key in the model the custom user model previously created. #project/api/models.py from django.contrib.postgres.fields import ArrayField from django.db import models from accounts.models import CustomUser class Signal(models.Model): name = models.CharField(max_length=30, blank=True, null=True) data = ArrayField(models.FloatField(), unique=True) threshold = models.FloatField(blank=True, null=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) def __str__(self) -> str: return f"{self.name}" while the project/api/views.py file is from django.template.defaultfilters import pluralize from rest_framework.decorators import api_view from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.request import Request from rest_framework.response import Response from . import serializers from .algorithm.compute_crossing import count_crossing_pos as count_cross from .models import Signal class SignalViewset(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Signal.objects.all() serializer_class = serializers.SignalSerializer def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class SignalDetail(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Signal.objects.all() serializer_class = serializers.SignalSerializer def get_queryset(self): return super().get_queryset().filter(user=self.request.user) @api_view(http_method_names=["POST"]) def send_data(request: Request) -> Response(): """send signal data with threshold in request payload and compute crossing times around given threshold :param … -
how to create Django model field for Transaction Number formate
Transaction Number - unique for each transaction Format - TRN/{COUNT}/{YEAR} Count here should reset to 1 for every year. -
Fetching current user in Django FormView
Im building a listings site and each user is linked to a company. Before the user can post a new listing it must have bought credits. If there are no credits the FormView should show a template with a notification of 0 credits, however if credits > 0 then the actual form with should appear. Im struggling in trying to fetch the current user in the FormView class itself. I know that it can be done via the form_valid method user = self.request.user, but that would mean that the user must first fill the whole form and submit it after checking if he has enough credits. Im tryiing to figure out how to perform the check before the form has been filled and submitted. I couldnt find any resources how can I do something like this: class CreateAd(LoginRequiredMixin, FormView): if currents_user.ad_credits > 0: template_name = 'ads/ad_form.html' form_class = AdForm success_url = '/' else: template_name = 'ads/not_enough_credits.html' form_class = AdForm success_url = '/' -
Django: request.is_ajax() returning False
I'm trying to make the search of 'patient' Dynamic with ajax. Every thing in my code is working well but I don't know wy request.is_ajax() always returns false. I search about it but I didn't find the solution yet, right now my code do the search but with changing of the url and that mean the js dosen't work. I don't know how work well with javascript in Django so please help me. This is my views.py: def index(request): ctx = {} url_parameter = request.GET.get("q") if url_parameter: queryset = Patient.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name')) patients = queryset.filter(fullname__icontains=url_parameter) #patients = Patient.objects.filter(name__icontains=url_parameter) else: patients = Patient.objects.all() ctx["patients"] = patients print(request.is_ajax()) if request.is_ajax(): html = render_to_string(template_name="patient/patients-results-partial.html",context={"patients": patients}) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, "patient/index.html", context=ctx) index.html: {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-4"> {# part added for dynamic search#} {# icon and search-box #} <form class="form-inline"> <i id="search-icon" class="fas fa-search" aria-hidden="true"></i> <input id="patient-input" class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" aria-label="Search" name="q"> </form> {# artist-list section #} <div id="replaceable-content" class="col-6"> {% include 'patient/patients-results-partial.html' %} </div> </div> <div class="col-md-6 offset-md-4"> <a href="{% url 'register_patient' %}" class="btn btn-primary">Ajouter un nouveau patient</a> </div> <div class="col-md-6 offset-md-4"> <div class="table-responsive"> <table class="table table-striped … -
Serialization in Django Rest Framework
In Django Rest Framework. I have a program that lets a user post some data. I serialize this input, but with this input I also save it to another model and create some default values for it and return them to the user. But I am getting slightly confused on whether or not I should serialize that model too. class FileExample(APIView): def post(self, request, format=None): serializer = FileExampleSerializer(data=request.data) if serializer.is_valid(): serializer.save() other_model = OtherModel(name=request.FILES['file'].name, type_obj='file') other_model.save() return Response({'url': other_model.url}, status=status.HTTP_201_CREATED) For example OtherModel is my other model object that I create which creates some default values. But I was looking at nested serializers but this did not achieve what I wanted, as it threw an error that it was missing a required value. My question is my code will work like this, but should I be serializing OtherModel as well? -
Django get uploaded images
I have created a model to get images and upload them to upload folder and the link is available in database. But when I call the image in my index.html it does not work settings.py USERFILES_DIRS = os.path.join(BASE_DIR, 'upload') STATIC_URL = '/static/' STATICFILES_DIRS = [ USERFILES_DIRS, os.path.join(BASE_DIR, 'static'), ] models.py class MyShoes(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=2) display_picture = models.ImageField(upload_to='upload', height_field=None,width_field=None, max_length=None) featured = models.BooleanField() views.py def myIndex(request): myShoes = models.MyShoes.objects.all() return render(request,'index.html',{'myshoes':myShoes}) HTML {% for x in myshoes %} <div class="card" style="width: 18rem;"> <img src="{{x.display_picture}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{x.title}}</h5> <p class="card-text">{{x.description}}</p> <p class="card-text">{{x.price}}</p> {{x.display_picture}} <a href="" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} here in my HTML i am getting the url 'upload/shoe-1384193-1279x850.jpg' but HTML does show it in img tag -
I need Mutiple fields from both models in an m2m .csv export
I have a working solution for exporting a .csv file from a join of 2 models via a manytomany relationship and my issue is I don't know how to express, in code, how to bring in multiple fields from the model that is being joined. I can add multiple columns from the model that has the m2m field defined but I can only bring in one column from the model that is being referenced. How do I bring in multiple coulmns from both models? models.py class dbmobile(models.Model): Site_Code = models.CharField('Site Code', max_length=20, blank=True, null=True, choices=SITE) Account_Number = models.CharField('Account Number', max_length=20, blank=True, null=True,) Mobile_Number = models.CharField('Mobile_Number', max_length=20, blank=True, null=True,) User_Name = CharField('User Name', max_length=120, blank=True, null=True,) User_id = models.CharField('User Id', max_length=20, blank=True, null=True,) class expense(models.Model): ExcludeTax = models.DecimalField('Exclude Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) IncludeTax = models.DecimalField('Include Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) user = models.ManyToManyField(dbmobile, blank=True) Date = models.DateField(default=now) views.py def export_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' employees = expense.objects.all() writer = csv.writer(response) writer.writerow (['Date', 'Tax Included', 'User']) for e in employees: writer.writerow([e.Date, e.IncludeTax, ', '.join([e.User_Name for e in e.user.all()]),]) return response -
Django Polls-App: dynamically change number of choices in create-poll-form
After completing the Django beginner tutorial, I managed to build a create form to create a new poll with multiple choices. Now i want to add a button that adds another text-field for another choice. I'm new to web development and i struggle with passing variables from templates to views. I read here: Passing variable from django template to view, that there are essentially 4 ways to do this. I am currently using option nr. 3 to specify the number of choices displayed, but i am sure that option 1 would be more elegant, hence the number of choices wouldn't be displayed in the url. This is my current code: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static "polls/style.css" %}"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ choice_forms.management_data }} <div class="pollschoice">{{ choice_forms.as_ul }}</div> <a href="{% url "polls:create" nr_of_choices|add:1 %}"><input type="button", value="Add Choice"> </a> <a href="{% url "polls:create" nr_of_choices|add:-1 %}"><input type="button", value="Remove Choice"> </a> <input type="submit", value="Save" /> </form> {% endblock %} def createview(request, nr_of_choices): # initialize forms nr_of_choices = max(nr_of_choices, 1) form = QuestionForm(request.POST or None) choiceFormSet = formset_factory(ChoiceForm, extra=nr_of_choices) choice_forms = choiceFormSet(request.POST or None) # save question …