Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django passing references to request/user django.contrib.auth.models
In this example Django code, how is request able to reference user? And user able to reference profile? p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) -
problemas con heroku
tengo un problema con heroku, ya se desplego la pagina pero al momento deentrar solo dice internal server error. ayuda, tengo 2 meses desplegando esta pagina https://watchalo.herokuapp.com/ intente desplegarla dos veces pero no pude hacer nada -
is there a way to diable django abstract base user is_staff and is_superuser fields
Is there a way to disable is_staff and is_superuser abstractbaseuser fields and instead use one user_role choice field to handle all permissions. -
Django and Celery testing issue
I use Celery in my Django (DRF) app to perform async tasks. Everything works fine, except the testing. The problem seems to be related to the APITestCase that it is executed before the Celery APITransactionTestCase deleting the database. Here a representative code: test_drf_views.py class DRFTestCase(APITestCase): @classmethod def setUpTestData(cls): ''' Init database ''' from myapp.init import init_data # this loads the database def setUp(self): self.login = reverse('login') # ... just a setup def test_foo(self): # ... just a test that works fine test_celery_task.py class CeleryTaskTestCase(APITransactionTestCase): @classmethod def setUpClass(cls): super().setUpClass() app.loader.import_module('celery.contrib.testing.tasks') cls.celery_worker = start_worker(app) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker.__exit__(None, None, None) def setUp(self): super().setUp() self.login = reverse('login') # here I call the DB and it FAIL The error I got when running pytest is: "matching query does not exists", because when the testing procedure reaches the test_celery_task.py the DB seems to be deleted. I also tried to reload the DB in the celery test, but nothing changes. Does anybody have an idea how to approach and solve the issue? -
How instanciate table in createsuperuser
I have two tables Employee and Sector, the employee table has for foreign key the sector code (sectorCode) property of the Sector table. The Employee table inherits from the AbstractBaseUser class. I would like to create a superuser with the command python manage.py createsuperuser. I get an error: ValueError: Cannot assign "'Code1'": "Employee.sectorCode" must be a "Sector" instance. (I added in the Sector table a row NameSector1; Code1) I input these values: λ python manage.py createsuperuser registrationNumber: 001 Name: TestN1 FirstName: TestFN1 sectorCode: Code1 Password: ... Error ... How can I instantiate sector class in dialog ? from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, registrationNumber, firstName, name, sectorCode, password=None): if not firstName: raise ValueError("firstName required") if not name: raise ValueError("name required") if not registrationNumber: raise ValueError("registrationNumber required") if not sectorCode: raise ValueError("sectorCode required") user=self.model(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode) user.set_password(password); user.save() return user def create_superuser(self, firstName, name, registrationNumber, sectorCode, password=None): user=self.create_user(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode, password = password) user.is_admin=True; user.is_superuser=True user.save() return user class Sector(models.Model): nameSector = models.CharField(verbose_name = "nameSector", max_length=50) sectorCode = models.CharField(verbose_name = "sectorCode", max_length=3, primary_key=True) class Meta: db_table … -
Why am I getting this Django custom command error: 'datetime.timezone' has no attribute 'now'
Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported it the same way. Do I have to import it differently since the command is in a different folder? (management/commands/) from django.core.management.base import BaseCommand from datetime import timezone, timedelta from gridsquid.models import User, Tile DEFAULT_TILE_IMG_NAME = "defaultsquid.svg" MAX_GUEST_ACCOUNT_DAYS = 30 class Command(BaseCommand): def handle(self, *args, **options): """ Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS """ # Get all guest accounts created before the limit expired_guests_count = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)).count() expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)) for guest in expired_guests: tiles = Tile.objects.select_related("user").filter(user=guest).all() for tile in tiles: # Delete image if not default image if DEFAULT_TILE_IMG_NAME not in tile.image.url: tile.image.delete() # Delete audio file if there is one if tile.audio is not None: tile.audio.delete() # Delete guest account guest.delete() -
Django: How do you use an image in your template and let your views.py know it was pressed like a button?
I want to show an image that the user can click on that will act like a button and return the data to my views.py. For example, <input type="submit" value="Add Selected Other Service to Included Service" class="button" name="Add Other Service"/> will create a very long button which I can "grab" in my views.py with: add_other_service = request.POST.get('Add Other Service') I can then test add_other_service and term if that was the button pressed. Hence, I can have multiple buttons on the page and determine which one as pressed. I know I can use the tag with the type="image" to click on the image, but I cannot find a way to get name of the button in the views.py. -
Django - How to encapsulate multiple values in a JSON Response?
I would like to know how I can put the following JsonResponse: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, }, safe=False) to something like this: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, { 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, } }, safe=False) Using the Django REST Framework. I simply want to encapsulate the result of two serializes inside the result of another to later unpack them properly at my Angular Frontend. How can I do this? Thanks in advance and kind regards :) -
Django Integration with React router dom
I am trying to serve web static files on my backend Django framework. I am using react with router Dom on my frontend and Django with rest framework. The problem now is that I am able to serve the page with route '' on Django but for other routes defined in frontend like posts are not able to be served on Django. Frontend react: App.js import React from 'react'; //import { Switch, Redirect } from 'react-router-dom'; //import { Navigate } from 'react-router-dom'; import "../stylesheets/templatemo-style.css"; // importing components from react-router-dom package // import { // BrowserRouter as Router, // Routes, // Route, // } from "react-router-dom"; import { HashRouter as Router, Route, Routes } from "react-router-dom"; // import Home component import Home from "./Home.js"; import User from "./User.js"; // import Post component import Comment from "./Comment.js"; import Post from "./Post.js"; import Account from "./Account.js"; //import User from "./components/User"; class App extends React.Component { render(){ return ( <> <div className = "App"> {/* This is the alias of BrowserRouter i.e. Router */} <Router> <Routes> <Route exaxt path = '' element={<Account/>} /> <Route path = 'posts'element={Post}/> </Routes> </Router> </div> </> ); } } export default App; And App is rendered in index.js import … -
Want to add '?id= ' in urls.py
I have urls.py in my project. I want to create URL like localhost:8000/v1/user?id=1 Can anyone help me how I can create the above URL. Thanks -
React-relay vs Apollo client for a react native app with Python-Django graphql backend
I am trying to build an app with react-native front end and django-graphene (graphql api) on the backend. Need some help to decide on pros/cons of using Apollo client vs React-relay for integrating the front end and backend which can be more efficient and scalable. Or if there are some other alternatives technology/libs which could be a great fit for loading data on the front end with graphql api on backend server. Any pointers on some great tutorials for the same would be very helpful. -
In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the foreign key User relation field
In the following mode in my project, I want to assign the author variable of class upon the creation of model, on user end this could be done via request.user but as the class can be only instantiated from the admin area, this doesn't work. class Blog(models.Model): title = models.CharField(max_length=300) content = RichTextField() author = models.ForeignKey(User, related_name="Author", auto_created= True, on_delete= models.CASCADE) date = models.DateTimeField(auto_now_add= True) -
Why and how is Django filter-by BooleanField query translated to SQL WHERE or WHERE NOT rather than 1/0?
I noticed that a query that used to be fast in legacy version of Django is now much slower in 4.0.8. There is a fairly large table with a FK 'marker' and a boolean 'flag' that has an index attached. The following queries could reasonably return tens of thousands of rows. In my codebase, there is a query like MyModel.objects.filter(marker_id=123, flag=False).count() In Django Debug Toolbar (and also in shell when I examine str(qs.query)) it now resolves to the following SQL syntax: SELECT ••• FROM `myapp_mymodel` WHERE (`myapp_mymodel`.`marker_id` = 123 AND NOT `myapp_mymodel`.`flag`) In extreme cases, this query runs for 20s or so. Meanwhile, in legacy Django version (1.11+) the same query becomes the following SQL: SELECT ••• FROM `myapp_mymodel` WHERE (`myapp_mymodel`.`marker_id` = 123 AND `myapp_mymodel`.`flag` = 0) This works, since the table schema contains 'flag' as a TINYINT(1), but most importantly, it works much faster - returning in under a second. Why is the difference in ORM-to-SQL translation, and where can I find the code responsible (I have checked db.backends.mysql to no avail, or failed to recognize the culprit)? Is there a way to hint to Django that I'd much prefer the equals-zero behaviour? The only workaround I see so … -
How to send binary as file using requests.request POST?
I have a field in db that contains binary (So i don't have a file, i have only it's representation as bytes). I have a server that is waiting file to be uploaded, so the question is how can i upload this bytes as file? How do i convert these bytes to file to send it to server? Example of what i have -> file = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x05\xd8\x00\x00\x018\x08\x06\x00\x00\x00HD\x91\x99\x00\x00\x0cmiCCPICC' Field in django that i need to be sent file = models.FileField(default='') I'm trying to do it like this -> tmp_file = open('tmp.pdf', 'wb') tmp_file.write(file) and then response = requests.request( "POST", url, headers=headers, data=payload, files={ 'file': ( open('tmp.pdf', 'rb'), ) } ) but i got error raise ValueError("Data must not be a string.") ValueError: Data must not be a string. Headers -> headers = { 'Authorization': 'Token ' + config['token'], 'Content-Type': 'application/json' } -
run automatically Nginx and Python script
I have a Django application that's lunched in Windows server 2016. using Nginx so my problem is I should start the application manually every time the server is rebooted. First I should open CMD and start Nginx.exe then I must run a python script in second CMD as python runserver.py -
redirecting to homepage after user submits a blog post?
I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly. here is the views.py: from django.shortcuts import render, redirect from .models import post from django.views import generic, View from django.views.decorators.http import require_GET from django.http import HttpResponse, HttpResponseRedirect from .forms import PostForm # Views for post list class postslist(generic.ListView): model = post queryset = post.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' paginate_by = 4 # view for individual post class postdetail(generic.DetailView): model = post template_name = "post.html" def blog_post(request): form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.save() return redirect("blog:success") context = {'form': form, } return render(request, "create_post.html", context) def success(request): return HttpResponseRedirect("home.html") urls.py: from . import views from django.urls import path, include from .views import * urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.blog_post, name='blog_post'), # success for blog post path('success/', views.success, name='success'), # posts path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), ] I have tried a few variations of httpresponseredirect and redirect but i just cant wrap my head … -
After setting up ssl I cannot access my site django&apache
I created a demo for my domain www.example.com which only returns the index as you can see below. def index(request): return HttpResponse("This is a demo") urlpatterns = [ path('admin/', admin.site.urls), path("",index), ] I was able to access my site with domain name (I made the "A" dns record in godaddy site) and this was the <VirtualHost *:80> <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> then I used "ssl for free" for creating a ssl certificate for my site and set the files they provided. <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com Redirect / https://loopingaround.com </VirtualHost> <VirtualHost *:443> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine SSLEngine on SSLCertificateFile /etc/ssl/certificate.crt SSLCertificateKeyFile /etc/ssl/private/private.key SSLCertificateChainFile /etc/ssl/ca_bundle.crt alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> now even if I revert the changes I made, I cannot access my site as … -
ModuleNotFoundError: No module named 'webapp.user'
at urls.py, I want to import webapp/user/views.py/ConfirmEmailView. so write code like this > from webapp.user.views import ConfirmEmailView and here is my Directory Structure.. but when I run this, error arises.. daesin_back-django-1 | Traceback (most recent call last): daesin_back-django-1 | File "manage.py", line 24, in <module> daesin_back-django-1 | main() daesin_back-django-1 | File "manage.py", line 19, in main daesin_back-django-1 | execute_from_command_line(sys.argv) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line daesin_back-django-1 | utility.execute() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute daesin_back-django-1 | self.fetch_command(subcommand).run_from_argv(self.argv) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv daesin_back-django-1 | self.execute(*args, **cmd_options) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 443, in execute daesin_back-django-1 | self.check() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 475, in check daesin_back-django-1 | all_issues = checks.run_checks( daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks daesin_back-django-1 | new_errors = check(app_configs=app_configs, databases=databases) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config daesin_back-django-1 | return check_resolver(resolver) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver daesin_back-django-1 | return check_method() daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check daesin_back-django-1 | for pattern in self.url_patterns: daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ daesin_back-django-1 | res = instance.__dict__[self.name] = self.func(instance) daesin_back-django-1 | File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 715, in url_patterns daesin_back-django-1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) daesin_back-django-1 … -
Getting information from a checkbox in Django
I have a problem getting data from a checkbox in my django project, I have this html instance: {% extends 'mailsinfo/layout.html' %} {% block title %} Add campaign page {% endblock %} {% block content %} <div class="parent"> <div class="child"> <form method="post"> {% csrf_token %} {{ form.name }}<br> {{ form.subject }}<br> {{ form.body }}<br> {{ form.user_guid }}<br> <span>{{ error }}</span> <button class="btn btn-success" type="submit">Save campaign</button> </form> </div> <div class="child"> <table id="table" data-height="540" class="table table-dark"> <thead> <tr> <th data-field="state" name = "selected" data-checkbox="true"></th> <th data-field="id">ID</th> <th data-field="email">Email</th> <th data-field="source">Source</th> <th data-field="created_at">Created at</th> <th data-field="modified_at">Modified at</th> </tr> </thead> </table> <script> var $table = $('#table') $(function() { var data = {{data|safe}} $table.bootstrapTable({data: data}) }) </script> </div> {% endblock %} Actions on this page are handled by this function: def add_campaign(request): error = '' if request.method == 'POST': formCanpaigns = CampaignsForm(request.POST) mails = request.POST.getlist('selected') print(mails) if formCanpaigns.is_valid(): formCanpaigns.save() return redirect('/') else: error = 'Form error' data = list(Emails.objects.values()) for i in data: i['created_at'] = i['created_at'].strftime("%m/%d/%Y, %H:%M:%S") i['modified_at'] = i['modified_at'].strftime("%m/%d/%Y, %H:%M:%S") i.pop("password") form = CampaignsForm() data_ = { 'form': form, 'error': error, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) Can you tell me how I can get data from the table where the checkbox is … -
Secure way to use Google Maps autocomplete with Django and React
I am currently building my first React Native app with a Django backend and it needs Google Maps autocomplete. Since GMaps is not a topic I know, I decided to look for some tutorials and so far I am worried since everything I find leaves the GMaps API key in the React app for it to work. The tricky part is that GMAP autocomplete, to the difference of other APIs, has an input component of its own so sending the input value from another input component to the backend, using requests to call the GMAP autocomplete API from there then sending back the results and at last maybe rebuild a list component made of the results will only result in getting the possible choices but not the rest of the input as it should be + I think it would be extremely costly in terms of performance for a React Native app. Does anyone know the right way to send the input request to my backend (where my Key must stay), make the request from there, then finally have the autocomplete working on my frontend? Or any other solution that would not expose my API key? Many thanks -
User account activation email - protocol repeated twice (django)
On this scenario, I am looking for the user to receive an email to activate their account. This email will contain a link for them to click on for the activation. For some reason the protocol "https://" is repeated twice in the email. In this case the code renders: "https://https://sitename.com/..." However, I do not encounter this problem when I run the code on my local host. I am using Django, and deploying on Heroku (just in case it matters). Here is the code. I tried removing rewriting "protocol": 'https' if request.is_secure() else 'http' #to "protocol": '' if request.is_secure() else 'http ' but no success, the protocol is repeated twice. Template {% autoescape off %} Hi, Please click on the link below to confirm your registration: {{ protocol }}://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} views def activate(request, uidb64, token): User = get_user_model() try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except: user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() messages.success(request, "Thank you for your email confirmation. Now you can log in your account.") return redirect('home') else: messages.error(request,"Activation link is invalid") return redirect('home') def activateEmail(request, user, to_email): mail_subject = "Activate your … -
How to get the top rated products in the following case?
I'm using Django==3.2 and Django-rest-framework==3.12.4 . I have two modals with following names Product and ProductRating. As you can see below class Product(models.Model): user = models.ForeignKey(User,related_name='userprofile', on_delete=models.CASCADE) name = models.CharField(("name"), max_length=50,null=True, blank=True) price = models.IntegerField(_("price"),default=0) create_time = models.DateTimeField(_("Create time"), default=timezone.now) class ProductRating(models.Model): user = models.ForeignKey(User, verbose_name=_("user"), on_delete=models.CASCADE,null=True,blank=True) product = models.ForeignKey(Product, verbose_name=_("product"), on_delete=models.CASCADE) stars = models.IntegerField(_("stars"),default=0) is_remove = models.BooleanField(_("is_remove"),default=False) create_time = models.DateTimeField(_("Create time"), default=timezone.now) Now I want to get the top rated products. According to the average rating of each product. the product that has highest rating and most count of reviews should appear first in the query list. I have tried the following thing but that just gave me those products who has any rating element. as you can see below. def get_all_top_rated_projects(self): query = self.filter(productrating__isnull=False) print( query[0].productrating.object.all()) I know its quite tricky case. I have tried to do it by myself. But i'm unable to do that. Anyone expert You can help and pull me out from this situation. Many Thanks In Advance. -
virtualenv env bash: virtualenv: command not found
I have a problem each time I want to start my VM even after Installing on windows ` $ pip install virtualenv Collecting virtualenv Using cached virtualenv-20.16.6-py3-none-any.whl (8.8 MB) Requirement already satisfied: platformdirs<3,>=2.4 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (2.5.2) Requirement already satisfied: distlib<1,>=0.3.6 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (0.3.6) Requirement already satisfied: filelock<4,>=3.4.1 in c:\users\samib\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from virtualenv) (3.8.0) Installing collected packages: virtualenv WARNING: The script virtualenv.exe is installed in 'C:\Users\samib\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed virtualenv-20.16.6 ` I have the error virtualenv env bash: virtualenv: command not found I tried to uninstall and install again but I have the same issue -
Django restframework convert json to model
I am new to Django and creating an API endpoint that will receive an incoming request, parse it, iterate the device list and make a request to another api. I have hardcoded the JSON structure but feel it may be better to user a serializer-type model to build the postbody, however, I have tried a few times and I am not successful or seeing how I would do this? Incoming Request Body: { "username" : "joe123", "devices" : ["iphone13", "laptop"] } The plan is to take this hardcoded example below and then make multiple requests to another API using the devices list requestBody = json.dumps(request.data) rawjson=json.loads(requestBody) print(rawjson['username']) print(rawjson['devices']) for alias in rawjson['devices']: postbody = { "alias": f"{alias}", "user-objects": [ { "name": f"{r['username']}]", "object-type": "byod" } ] } headers = { 'Authorization': 'Basic dGVzdDp0ZXN0Cg==' } response = requests.request("POST", url, headers=headers, data=postbody, verify=False) r_status = response.status_code .... ....etc So I created a serializers.py file and added the following: from rest_framework import serializers class UserObjectsSerializer(serializers.Serializer): username = serializers.CharField() object-type = serializers.CharField() class AliasSerializer(serializers.Serializer): alias = serializers.CharField() user-objects = UserObjectsSerializer(many=True) I am unsure how I correctly map the incoming username and devices list from the json object to this class-based object, so I can … -
python+django-unchecked checkbox returns "none"
I have an HTML form with checkbox: <form action="...function x" method="POST"> {% for x in box %} <tr class="cart_row_{{forloop.counter0}}"name="cart_row_{{forloop.counter0}}"> <td> <input class="form-check-input" type="checkbox"value="-1" checked="0" name="check_{{forloop.counter0}}"> <label class="form-check-label" for="check_{{forloop.counter0}}">Select item</label> </td> </tr> {% endfor %} <input type="submit" value="Checkout"> </form> When the checkbox is checked, everything works fine. When the checkbox isn't checked, django returns this error: TypeError at ...:'NoneType' object is not iterable The cause of the error is that the checkbox value is "none". How can I get over this?