Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django db rounting for prefetch_related
The raw SQL of this Django query has two SQL sentences. Would it use the same database for these 2 sentences? Django query: brands = (Brand.objects.using('default') .prefetch_related('product_set') .select_related('vendor') .filter(id__in=(1000, 1100)) ) SQL: SELECT * FROM `vendors_brand` LEFT OUTER JOIN `vendors_vendor` ON (`vendors_brand`.`vendor_id` = `vendors_vendor`.`id`) WHERE `vendors_brand`.`id` IN (1000, 1100) SELECT * FROM `products_product` WHERE `products_product`.`brand_id` IN (1100, 1000) I have 3 databases for my Django project: read1, read2 and default. And the router selects these 3 databases randomly for reading and uses only default for writing. I designated default for some queries with using(), but it seems that using() does not use the default all the time. -
Django taggit related post not showing on template
Recently I installed django-taggit and included in the post model. I did the views and urls files and no error. On the home page I get a few posts and 10 tags related to posts. When I click on one of the tags it goes to the right slug but the page is blank. What am I missing here? Any help would be appreciated. This is my code, views.py, urls.py, home.html def home(request): tutorial_list = Post.objects.all().order_by('-id')[:3] context = { 'tutorial_list': tutorial_list, } return render(request, "home.html", context) class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class TagIndexView(TagMixin, ListView): template_name = 'home.html' model = Post context_object_name = 'post' def get_queryset(self): return Post.objects.filter(tags__slug=self.kwargs.get('slug')) '''urls.py''' path('tag/<slug:slug>/', views.TagIndexView.as_view(), name='tagged'), '''home.html''' {% for tutorial in tutorial_list %} {{ tutorial.title }} {% endfor %} {% for tag in tags %} <li><a href="{% url 'tagged' tag.slug %}">{{ tag.name }}</a></li> {% endfor %} -
How to parse json payload in html form formate to an api in django and perform calculation
I want to parse the The parameters below to an endpoint for payment and upon a successful payment, the amount added to a a model field in my database. Parameters are " merchant_id, transaction_id, amount, API_Key, apiuser, email, redirect_url " and the api " https://test.theteller.net " I have a model that i want the amount enter by a user to be save to the vote filed upon successful payment. model.py class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Nominee_ID = models.CharField(max_length=100) Category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='nominations_images') slug = models.SlugField(max_length=150) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Fullname View.py class NominationView(ListView): model = Category template_name = 'nomination.html' class NominationPayView(DetailView): model = Nomination template_name = 'Payment.html' Payment.html <form action="https://test.theteller.net " post="post"> <input type="text" name="merchant_id" id="merchant_id" value=""> <input type="text" name="transaction_id" id="transaction_id" value="{{ nomination.Nominee_ID }}" > ... <button type="submit" >Submit</button> </form> AM processing the form on the detailView because i want the amount saved to the element being viewed. 1. I would like to pass the parameters to the API endpoint successfully. 2. Then save the amount to vote field in the nomination upon … -
CBV: How To Make A Drop Down Database Query Using Django FormView
What I would like to do is have a dropdown list containing objects from a database. When the user selects an object, I would like the information displayed on the page. What I have been able to do is have the values shown in the dropdown list, but I have not been able to display the way I'd like. I've been trying to do so a certain way to hopefully be able to better control the look of the form. models.py class Vehicle(models.Model): make = models.CharField(max_length=20) model = models.CharField(max_length=20) def __str__(self): return self.make + ' ' + self.model class Package(models.Model): make_model = models.ForeignKey( Vehicle, on_delete=models.CASCADE ) name = models.CharField(max_length=20) price = models.IntegerField() views.py class VehicleCompareView(FormView): template_name = "main/somehtml.html" form_class = forms.CompareForm forms.py objectlist = forms.ModelChoiceField(queryset=models.Package.objects.all() \ .order_by('make_model__make')) html file <form method="GET"> <select class="form-control"> <option value="0" selected disabled>Select Vehicle 1</option> {% for q in form.objectlist %} <option value="{{q.name}}">{{ q.make_model__make }}</option> {% endfor %} </select> </form> <div> <p>Selected Vehicle: {{q.make_model__make}} {{q.make_model__model}}<br> Price: ${{q.price}} </p> </div> So let's start with what I have found that somewhat works from messing with the code. If I use {{form}}, I get the package list, but it only displays the package name of course. If I attempt … -
How To Make Form Field Read Only In Template Django
I am curious how I can make a field read only in my template below or via the form? <div class="column"> <label for="form.reference" class="formlabels">Reference ID: </label><br> <!-- <input type="text" value="{{ reference_id }}" readonly>--> {{ form.reference }} </div> forms.py class CreateManifestForm(forms.ModelForm): cases = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter Cases'})) class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') widgets={ 'product_name': forms.Select(attrs={'style': 'width:170px'}) } I know I could do it the way that I commented out in the template, but I don't want to specifically define the input field like that. So how can I make it so that ```{{ form.reference }} is read only? -
Django with Elm Language
How would you combine Django with Elm? For example when you use Django's List and Detail generic view with templates but want to inject Elm for reactivity? -
How to create signals with guardian and Django
After a user registers and answers a few survey questions for the site, then I want to give access to a view. I'm using guardian to provide access. Currently Django just takes me to a blank page, when I test this. This view asks users to answer a few questions and then I assign the permission view page to the user. Then in the view 'genre_book' I only want it to be viewable for users assigned with the view_page permission. This does not work, but generates a blank page. #view to create the guardian permission def agreements_page(request): if request.method == "POST": form = AgreementsForm(request.POST) if form.is_valid(): user = request.user if user.is_authenticated: agree = form.save(commit=False) agree.user = request.user agree.save() assign_perm('view_page', user, agree) return redirect('page') else: return redirect('other_page') else: form = AgreementsForm() return render(request, 'agreements.html', {'form': form}) Here is the view that I want to restrict to users who have filled the agreements form. @permission_required('view_page') def genre_book(request, pk): .... # this is a function that deploys the page -
Cannot import models into Celery tasks in Django
I am trying to configure Django and Celery and am running into an issue when I import the task into the models.py file and simultaneously import a model into the tasks.py file. Celery is otherwise working. See code below... core/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) users/models.py from django.db import models from core.tasks import celery_test #this triggers the error class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) def __str__(self): return self.email core/tasks.py from celery.decorators import task from users.models import CustomUser @task(name="celery_test_task") def celery_test_task(): print(CustomUser) core/settings/base.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' Here is the error message: File "...\src\users\models.py", line 6, in <module> from core.tasks import celery_test File "...\src\core\tasks.py", line 2, in <module> from users.models import CustomUser ImportError: cannot import name 'CustomUser' from 'users.models' (...\src\users\models.py) -
Django with Postgresql: duplicated objects created on local machine and triplicated objects on remote server
I have a Django project with Postgresql on DigitalOcean. Strangely, when I create an object it's triplicated on the remote server and duplicated on the local machine. Here are my models. from django.db import models class Instrument(models.Model): id = models.CharField(max_length=4, blank=False, primary_key=True) def __str__(self): return self.id class Quote(models.Model): instrument = models.ForeignKey(Instrument, null=False, blank=False, on_delete=models.CASCADE, related_name='quotes') quote = models.FloatField(blank=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.instrument.id; And this is how I create an object: q = Quote(instrument=Instrument.objects.get(pk='GBP/USD'), quote=1.2100) q.save() I tried creating objects in different ways: i = Instrument.objects.get(pk='EUR/USD') q = Quote.objects.create(instrument=i, quote=1,2000) I would appreciate any comments and ideas how to resolve it. -
How to implement a google-login for any google APIs in a Django wep-app?
I'm currently developing a Django web app that will allow users to sign-in with their google account and get access to their Google Calendar and Google Drive data. I already succeeded in doing so on another project in a front-end context using an Angular library called ng-gapi (GoogleAuthService) but I can't seem to find an equivalent for Django! All I was able to do for the moment is to implement a simple google login, but can't communicate with the different google APIs. I have tried to use a module called django-allauth but it only logs-in the user via google but without providing any useful information (like authorization tokens etc...) needed to grant the web app to communicate with the user's google data. {% load socialaccount %} {% providers_media_js %} {% load static %} <html> <body> {% if user.is_authenticated %} <p>Welcome {{ user.username }}</p> <a class="btn btn-warning" href="http://localhost:8000/accounts/logout/">Log out</a> <a class="btn btn-secondary" href="http://localhost:8000/show/">My Gigs</a> <p>You're logged in with {{ user.get_provider }} as {{ user }}.</p> <img style="max-width: 80px; padding:10px; margin-bottom:10px" src="{{ user.socialaccount_set.all.0.get_avatar_url }}" /> <p>UID: {{ user.socialaccount_set.all.0.uid }}</p> <p>Date Joined: {{ user.socialaccount_set.all.0.date_joined}}</p> <p>Last Login: {{ user.socialaccount_set.all.0.last_login}}</p> <p>{{ user.socialaccount_set.all.0.extra_data.name }}</p> {% else %} <a class="btn btn-primary" href="{% provider_login_url 'google' %}">Log in</a> {% … -
Postgres DB getting overloaded when generating a sitemap in Django
I am generating a sitemap for a Django model. However, the Postgres DB gets overloaded filtering the table we're indexing. This causes the site to experience downtime for hours, because the database is backed up. The exact query causing the issue is: Books.objects.all().exclude(has_kindle__isnull=True).order_by('-has_kindle', '-id').select_related('publisher') The table has 3M rows, and the results are about 300k, divided into separate smaller sitemaps, each with 10k links each. Is it normal for the query above to cause the database to totally seize up like that? Is there anything wrong with this query that could be optimized? Any and all ideas much appreciated! -
How to fix 'the file is not displayed in the editor because either banary or ...' error in vs-code
I have added a file of fonts to my django project which contains fonts and when i went to the browser to see the result the font that i have been added didn't appear and in the editor it appeared this message and i appologize for my english language -
Is there a method to check the url a person is coming from?
I am currently designing a simple e-commerce store with django. I have my payment page and checkout page in two different views. Is it possible to only render the payment page if and only if the user came from the checkout page. -
EMAIL ERROR Help me handle the syntax error
I tried to send a confirmation message to my gmail account and I encountered an error which says "SMTPAuthenticationError at /password-reset/" SETTINGS.PY CODES 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('DB_USER') EMAIL_HOST_PASSWORD = os.environ.get('DB_PASSWORD') from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view (template_name='users/password_reset_done.html'), name='password_rest_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('', include('blog.urls')), i expected it to send an email...but i had an error ........................................ SMTPAuthenticationError at /password-reset/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials r5sm435188wmh.35 - gsmtp') Request Method: POST Request URL: http://127.0.0.1:8000/password-reset/ Django Version: 2.1 Exception Type: SMTPAuthenticationError Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials r5sm435188wmh.35 - gsmtp') Exception Location: C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py in auth, line 642 Python Executable: C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\NAGwizz\desktop\project', 'C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32', 'C:\Users\NAGwizz\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\NAGwizz\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Mon, 26 Aug 2019 20:56:01 +0000 -
Error using pickle.load on sklearn VotingClassifier
I'm trying to store a trained ML model using pickle.dump(ML_model) to use it on a website built with django. When doing that with e.g. logistic regression everything works fine. However when doing that with the sklearn VotingClassifier I get the following error when using pickle.load(my_stored_voting_classifier): ModuleNotFoundError at ... No module named 'sklearn.ensemble.voting' Request Method: POST Request URL: http://localhost:8000/.... Django Version: 2.1.7 Exception Type: ModuleNotFoundError Exception Value: No module named 'sklearn.ensemble.voting' Exception Location: ...views.py in ... Python Executable: ...python Python Version: 3.6.8 Store the model: where eclf is the classifier model_name = "votingensemble1" path = f'/.../.../{model_name}' with open(path, 'wb') as file: pickle.dump(eclf, file) Load the model: path = '/.../.../votingensemble1' with open(path, 'rb') as model: ml_model = pickle.load(model) -
NoReverseMatch at /shop/ django
I have an error on my site (http://datat.ru/shop/) Reverse for 'shop_detail' not found. 'shop_detail' is not a valid view function or pattern name. How can I solve it? This is my code. I checked <h1><a href="{% url 'shop_detail' pk=shop.pk %}">{{shop.title}}</h1> it seems ok. I think that problem deals with urls.py, but didn't find it( urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.post_list, name='post_list'), path('shop/', views.shop_list, name='shop'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('shop/<int:pk>/', views.shop_detail, name='shop_detail'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post, Company def post_list(request): posts = Post.objects.all() return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def shop_list(request): shops = Company.objects.all() return render(request, 'blog/shop_list.html', {'shops': shops}) def shop_detail(request, pk): shop = get_object_or_404(Company, pk=pk) return render(request, 'blog/shop_detail.html', {'shop': shop}) html <div class="container" style="margin:40px;"> <div class="row"> <!--<div class="col-12 col-sm-8 col-lg-5">--> <div class="col-sm-12"> <h6 class="text-muted">List Group with Cards</h6> <ul class="list-group"> {% for shop in shops %} <li class="list-group-item d-flex justify-content-between align-items-center"> <!-- Vacancy start --> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-8"> <h1><a href="{% url 'shop_detail' pk=shop.pk %}">{{shop.title}}</h1> … -
how can i sign up with custom user model (One By One Type) in django?
how can i create a correct sign-in And sign-up with custom user model(OneToOneField) in django ? im using normal HTML form . im using Django 2.2.3 . my database is Postgeres. hi, i created a website that sign in and sign up where ok , But ... i needed custom user model .. so i created a custom user model (using one on one field ) , but i don't know how to create sign-in and sign-up for it... so i tryed ... but it won't work correctly... i can't make a sign up with additional fields in my custom user model , it sign up with only User , not Profile and gives me this error "'Manager' object has no attribute 'create_profile'". and for my sign-in .. i think its sign-in with Django's User. im using Django 2.2.3 . my database is Postgeres. how can i create a correct sign-in And sign-up ? my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) address = models.TextField(max_length=500) phone = models.CharField(max_length=50) postcode = models.CharField(max_length=50, blank=True) isManager = models.BooleanField(default=False) isAccountment = models.BooleanField(default=False) isStorekeeper = models.BooleanField(default=False) isSeller = models.BooleanField(default=False) isNormal … -
How to handle errors when using PasswordResetConfirmView
I am using django.auth.contrib as my session based authentication framework. I have successfully implemented a reset password feature via PasswordResetConfirmView which requires a valid token sent to a user's email to set a new password. path('password_reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset/password_reset_confirm.html'), name='password_reset_confirm'), This works fine if the token is valid. However, if the token is not valid (e.g. incorrect or expired), then I predictably get an error: Reverse for 'password_reset_confirm' with arguments '('', '')' not found. 1 pattern(s) tried: ['accounts/password_reset/confirm/(?P[^/]+)/(?P[^/]+)/$'] What's the best practice to handle this exception for the user? Ideally I want to catch it and intercept it with "Sorry, your token is invalid." Is there an existing way to do this within the django.contrib.auth framework? Looking for the best DRY approach. -
list all Input fields generated dynamically on django
I have a problem that I want to solve when I add many Input dynamic for example five input How do I know to list all Input fields generated dynamically on django knowing that I get one field by name only date=form.cleaned_data.get('date') The problem is illustrated in the following form: -
django 2.2.4 from __future__ import unicode_literals
I'm using Django version 2.2.4 with the code below. In terminal I'm not getting any error messages, however, after creating a new profile in the admin section, instead of displaying the name of the new profile 'profile Object 1' is displayed. 'return self.name' is suppose to get the name from the newly created profile and display it. Please view picture for a clear understanding. from __future__ import unicode_literals from django.db import models # Create your models here. class Profile(models.Model): name = models.CharField(max_length=120) description = models.TextField(default='description default text') def __unicode__(self): return self.name -
Django max post size triggered for small request?
I have some requests triggering this issue... From my main Apache log: [Mon Aug 26 20:03:48.793674 2019] [wsgi:error] [pid 50973:tid 140470815614720] [remote 207.136.212.82:60947] ERROR Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. ... and from my access log: localhost:443 207.136.212.82 - - [26/Aug/2019:20:03:48 +0000] "POST /en/log HTTP/1.1" 400 539 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148" That 539 bytes should be well below the Django setting: (InteractiveConsole) from django.conf import settings settings.DATA_UPLOAD_MAX_MEMORY_SIZE 2621440 What could be triggering this check for such a small request? -
Weird redirect behavior
I am getting inconsistent behaviors from my Django template on different browsers. Here is the form: <div class="login-form center"> <div class="form-group"> <input type="text" class="form-control login-field" value="" placeholder="Enter your Worker-ID here" id="user-id"> <label class="login-field-icon fui-user" for="user-id"></label> </div> <a id="btn-login" class="btn btn-primary btn-lg btn-block">Next</a> </div> and the related javascript: $(document).ready(function() { $('#btn-login').click(click_event); }); function click_event() { csrfSetup(); let user_id = $('#user-id').val(); if (!user_id) { alert("Please enter your username!") } else { $.post("/snli/api/auth_login/", { "username": user_id, }, login_callback); } } function login_callback(message) { // do more stuff window.location.href = '/snli/human_annotations/'; // <-- the redirect } On Chrome, it gets redirected to http://localhost:8000/snli/human_annotations/ On Firefox, it gets redirected to http://localhost:8000/login/?next=/snli/human_annotations/ and then gets stuck on "page not found" Any thoughts what causes this the difference? (and how to resolve it?) -
For loop and django save not working with Django mail delivery system on live server
I have created a mail delivery system that can deliver tips to 3 different countries. Tips for all the customers are saved in a table which also includes the country. I call the function using the url http://127.0.0.1:8000/cls/mail/?region=Americas and pass the region via the URL. There are 18 customers from Asia and 79 from the Americas. The issue I'm facing is when this function is run it needs to find the tip sequence for that week and load it to the mail queue table. All of this works in the local host everything works perfectly fine. But when I load to the digital ocean server only the tips for American customer does not work. I get this error: This page isn’t working 167.71.231.108 didn’t send any data. ERR_EMPTY_RESPONSE While during my debugging process I have realised that if there are more than 28 customers for a country the get function does not work. I feel like I have exhausted all my tries. Any help with this would be highly appreciated. Thank you class MailView( TemplateView): template_name = 'emailTemplate.html' def get(self, request, **kwargs): ###print("TEXXXXXXXXXXXXXX - " + str(request.GET.get('region'))) context = super(MailView, self).get_context_data(**kwargs) if request.GET.get('region') == None: return HttpResponseBadRequest("No Region") else: subscriber_tipqueue_instances … -
How to handle permissions/validation in django.auth.contrib
When implementing django.auth.contrib there are a number of views such as password_reset_done that should only be visible after a specific action (each following on from a successful form submission). However there does not appear to be any inbuilt validation/authentication of these specific use cases. What's the best practice for handling these views? Should we subclass the class view? Have I missed a built in function? -
Django how to add an initial value with modelformset_factory?
How can I pass an initial value to Product_Form when using it with modelformset_factory? This is my attempt: models.py: from django.db import models class Product(models.Model): name = models.CharField(max_length=45) qty = models.IntegerField() price = models.IntegerField() forms.py: from django import forms from .models import Product class ProductForm(forms.BaseModelFormSet): def __init__(self, *args, **kwargs): super(Product_Form, self).__init__(*args, **kwargs) qty = kwargs.get('qty','') print(qty) #prints blank string self.queryset = Product.objects.filter(qty=qty) class Meta: model = Product fields = ['name', 'qty', 'price'] views.py: from django.shortcuts import render from django.views import View from django.forms import modelformset_factory from .forms import Product_Form from .models import Product class Inventory(View): def __init__(self): pass def get(self, req): product_form = modelformset_factory(Product, fields=('qty','price','name'), formset=Product_Form) form = product_form(initial=[ {'qty':0}, ]) context = { 'form':form, } return render(req, 'base.html', context) the data I need to pass to it is the result of a Search_Form, (IE user input) which is used to filter the Products query. When I try to render base.py, I get the following error: invalid literal for int() with base 10: '' Which appears to be due to the fact that an empty string is being inserted into Product.objects.filter(qty='') I am taking most of this code directly from the docs, so I'm really not sure why it isn't …