Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any package or function save csv file in database table format
Scenario: User upload the CSV file and in the backend save CSV as a file. Now I am trying to save those csv file in database as a table format. When csv save database it will show the data like pandas dataframe. I already see some packages like django-import-export. But it will not that i want. The main thing is that in that packages create the model before uploading the file. But i don't create model before user uploading file. here is my django code. model.py from django.db import models # Create your models here. from django.db import models # Create your models here. class DataUpload(models.Model): fileId = models.AutoField(primary_key=True) data_upload = models.FileField(upload_to='files/') class Meta: db_table = 'DataUpload' forms.py from django import forms from .models import DataUpload class PostForm(forms.ModelForm): class Meta: model = DataUpload fields = ['data_upload'] urls.py from django.urls import path from .views import dataview , FileView, ResultView # from .views import BonolothaDataView urlpatterns = [ path('', dataview.as_view()), path('fileview/', FileView.as_view(), name='fileview'), path('result/', ResultView.viewResult, name='result'), # path('bonolotha/', BonolothaDataView.as_view(), name='bonolotha'), ] views.py class dataview(View): model = DataUpload form_class = PostForm initial = {'key': 'value'} template_name = 'post.html' fileview_url = reverse_lazy('fileview') def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) # pribt html form … -
Django: Remove form fileds based on some values in the database
I want to remove some fields from a form based on some values in the database. I'm not using this form to insert the data into any database, I'm going to make a csv file from this form data. Also this form is not related to any model. forms.py class Registration_form(forms.Form): Applicant_Name = forms.CharField(label='Your name', max_length=100) Applicant_age = forms.IntegerField(label ='Age of Applicant') Applicant_email =forms.EmailField(max_length=50) Applicant_phone = forms.CharField(max_length=10) views.py class Registration_View(FormView): template_name = 'EVENTAPP/Application.html' form_class = Registration_form success_url = '/' def form_valid(self, form): Applicant_Name = form.cleaned_data['Applicant_Name'], Applicant_age=form.cleaned_data['Applicant_age'], Applicant_email=form.cleaned_data['Applicant_email'] Applicant_phone=form.cleaned_data['Applicant_phone'] # do some operations if form data valid return super().form_valid(form) models.py class es_event(models.Model): ev_name = models.CharField(max_length=100,verbose_name="Event Name") ev_date = models.DateField(auto_now=False, verbose_name="Date") ev_description = models.TextField(null=True, verbose_name="Description") registrant_name = models.BooleanField(default=True ) registrant_age = models.BooleanField(default=False) registrant_phone = models.BooleanField(default=False) registrant_email = models.BooleanField(default=False) registrant_institution = models.BooleanField(default=False) name = models.CharField(max_length=100,null=True) reg_open = True slug = models.SlugField(max_length=250) def save(self, *args, **kwargs): self.slug = slugify(self.ev_name) return super(es_event, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('event_detail', kwargs={'id': self.id, 'slug': self.slug }) urls.py url(r'^events/register(?P<id>\d+)(?:/(?P<slug>[\w\d-]+))?/$', views.Registration_View.as_view(), name='event_application') Now what I want to do is find a particular instance of es_event from the database by using the value of "id" in the URL. Then if that instance has the attributes registrant_name,registrant_age, etc is True then the … -
How to send multiple objects through request in django?
I have created a views function in django which returns the data of all cars. Now I want to add the functionality that a user can make multiple lists and then add those cars to any of the list created by them. The lists created by the users are displayed in the form of a drop down menu in front of the car name. How should I send the list information to be displayed according to the user in front of the car name in django rest framework. P.S: I am new to using django rest framework. -
How to create sign up form for customer user model in Django?
I have extended the User Model provided by Django into Owner object. What I intend to do, is create a sign up form which creates a new user in my application and also fill up the custom fields defined in Owner object. My code is as follows - model.py - class Owner(BaseModel): id = models.AutoField(primary_key=True) gym = models.ForeignKey(Gym, on_delete = models.CASCADE) # User model user = models.OneToOneField(User, on_delete = models.CASCADE) address = models.OneToOneField('Address', on_delete=models.CASCADE) contact = models.BigIntegerField(null=False) dob = models.DateTimeField(null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, default=None) profile_photo = models.ImageField( upload_to='static/images/gym_owner/profile', null=True, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name_plural = "Owner" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Owner.objects.create(user=instance) instance.profile.save() SO basically, Owner model extends the User model via One-to-One relationship method. And there is a signal receiver method which creates the Owner object when User object is created. Forms.py - class OwnerForm(ModelForm): class Meta: model = Owner fields = ('gym', 'address', 'contact', 'gender', 'profile_photo') The form basically contains the fields that I want to extend the User model with. And the view.py - @transaction.atomic def owner_signup(request): if request.user.is_authenticated: return redirect('dashboard') if request.method == 'GET': userForm = UserCreationForm() ownerForm = OwnerForm() return render(request, 'gym_owner/signup.html', {'userform': userForm, 'ownerForm': … -
How to convert Django template to pdf and download it locally
I want to convert and download django template to pdf file. I run my function using console. The function is as follows: def generate_windscreen_pdf(lead_ids): for lead_id in lead_ids: language = settings.DEFAULT_CULTURE_MAJOR translation.activate(language) car = map_lead(lead_id, 0) translate_dict_recursive(car, language) s_template = 'manager/seller/templates/pdf/windscreen.html' context = {'car': car, 'note': note} html_template = render_to_string(s_template, context) translation.deactivate() pdf_file = HTML(string=html_template).write_pdf(stylesheets=[CSS(string='@page { size: A4 landscape; margin: 0.2cm }')]) response = HttpResponse(pdf_file, content_type='application/pdf', mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename="windscreen_{0}.pdf"'.format(lead_id) return response And the template is as follows: <html> <head> <link rel="stylesheet" href="{{ car.header_css }}"> </head> <body> <div class="header"> <img src='{{ car.make }}' /> </div> I'm using weasyprint library. When I run it from the console I get the output as follows: Fontconfig warning: "/usr/local/etc/fonts/fonts.conf", line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf Fontconfig warning: "/usr/local/etc/fonts/fonts.conf", line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf <django.http.HttpResponse object at 0x10ad19f10> But I want that the file is downloaded to the folder on my local pc. Any idea how to do that? -
Picture Upload Form didnt show a image upload column
I have a CreateView for Post where I have a title and content columns, I tried to add image upload column for that post and it wont works, but it wont shows an error, so I don't know what I'm doing wrong... I migrated it and it wont show an column for upload picture. Here are my codes. views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(LoginRequiredMixin, DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): form_class = PostUpdateForm model = Post fields = ['title', 'content', 'image'] forms.py class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['image'] models.py class Post(models.Model): title = models.CharField(max_length=100, verbose_name='タイトル') content = models.TextField(verbose_name='内容') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='uploaded_pic') def __str__(self): return self.title def get_absolute_url(self): return reverse('Post-detail', kwargs={'pk': self.pk}) post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form enctype="multipart/form-data method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">ブログ投稿</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">投稿</button> </div> </form> </div> {% … -
How to perform content negotiation in django middleware?
Let say i have a Custom Django Middleware which check request header has jwt token if not return rest_framework Response., middleware.py @staticmethod def process_view(request, view_func, view_args, view_kwargs): try: jwt_token = request.headers["token"] except KeyError: response = Response(status=status.HTTP_403_FORBIDDEN) return response but i am getting error like .accepted_renderer not set on Response how to perform content-negotiation here? -
How to additional field to Django Oscar Order model?
I want add additional field to Order model. i have already forked order app. below is the code added in Order model in forked_app Order app. from django.utils import timezone from oscar.apps.order.abstract_models import AbstractOrder from oscar.apps.order.models import * # noqa isort:skip from django.db import models class Order(AbstractOrder): status_update_time = models.CharField(max_length=30) def save(self, *args, **kwargs): self.status_update_time = timezone.now() super(Order, self).save(*args, **kwargs) Below is the error i get while migrations. class Order(AbstractOrder): NameError: name 'AbstractOrder' is not defined Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f06737e6d08> RuntimeError: Conflicting 'order' models in application 'order': <class 'oscar.apps.order.models.Order'> and <class 'forked_apps.order.models.Order'>. -
Firebase phone authenticatin with django rest framework
I am developing APIs for an app where it is required to do firebase phone authentication from server side. I am using Djanngo Rest Framework for APIs I did some research for this and only found for email and password authentication. Found none for phone authentication. Is there any way in which I can do phone authentication from server side. -
How are my html templates able to get the username without any arguments passed by views.py?
I have a djongo engine based google authentication applications My views.py renders the homepage, without passing any arguments: return render(request=request,template_name="mainapp/homepage.html") And homepage.html looks like: <html> <head></head> <body bgcolor = "green"> <p>THIS IS THE HOMEPAGE</p> {% if user.is_authenticated %} <p class="display-4">Hello, {{ user.username }} you are signed in</p> <a href="/account/logout">Log out</a> {% else %} <a href={% url "social:begin" "google-oauth2" %}>Login with Google</a> <p>Not signed in</p> {% endif %} </body> </html> Yet after the user logs in it shows the correct username( not that of the admin). -
How to call function if http request is POST in Django views and pass new submitted file name to function call?
I'm working on web application in which user upload a video and we perform speech recognition on it and then translate its text in another language.So, if the request is POST then we call that function which perform these functionalities and if request is GET it should not call that but in my case,on POST request, function execute first and then POST request is submitted.And it perform functionality on the last video in database. It gives the same result even if I put function call at the end of POST request condition statement and if I put function call out of POST request condition the function call on every reload of page which is not required and I don't know other ways how to solve this problem. """ Django==2.0.2 views.py""" def generatingsubtitle(request): latestvideo = Video.objects.last() videofile = latestvideo.videofile path = settings.MEDIA_ROOT + videofile.name filename = os.path.splitext(videofile.name)[0] srtpath=settings.STATIC_ROOT+filename if request.method == 'POST': #function call main(path, srtpath) form = forms.VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('generatingsubtitle'), ) else: form = VideoForm() return render(request, 'app/generate.html', { 'form': form, 'videofile': videofile, 'filename':filename, }, ) I expect that ,POST request is submitted first and we take path of newly submitted file … -
How to fix "object() takes no parameters" error in Django
I am trying to access my database called Active_Project_View. Inside of this is the information I am trying to display in ag-grid. I have used the objects.all() to get the information out but it's not work. class getActiveGrid(): def get_queryset(self, request, format=None): queryset = Active_Project_View.objects.all() return queryset def get(self, request, format=None): filters = request.data serializer = ActiveGridViewSerializer(self.get_queryset(filters), many=True) return HttpResponse(serializer.data) <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="static\app\content\agGrid.css" > <script src="https://unpkg.com/ag-grid-community/dist/ag-grid- community.min.noStyle.js"></script> <link rel="stylesheet" href="https://unpkg.com/ag-grid- community/dist/styles/ag-grid.css"> <link rel="stylesheet" href="https://unpkg.com/ag-grid- community/dist/styles/ag-theme-balham.css"> </head> <body> <h1>Project Grids</h1> <div class="box c"> Active Projects <script type="text/javascript" charset="utf-8"> const Active_Project = [ { headerName: "Last Name", field: "app.Customer_Last_Name", sort: 'asc' }, { headerName: "First Name", field: "Customer_First_Name", }, { headerName: "Phone Number", field: "Customer_Phone_Number", }, { headerName: 'Employee', field: 'Employee_First_Name' }, { headerName: 'Zip Code', field: 'Customer_Zip' }, ]; const ActiveProjectGrid = { columnDefs: Active_Project, }; var eGridDiv1 = document.querySelector('#ActiveProjectGrid'); new agGrid.Grid(eGridDiv1, ActiveProjectGrid); fetch('getActiveGrid').then(function (response) { return response.data(); }).then(function (data) { ActiveProjectGrid.api.setRowData(data); }) </script> </body> </html> url(r'^getActiveGrid$',app.views.getActiveGrid, name='postActive'), class ActiveGridViewSerializer(): class Meta: model = Active_Project_View fields= '__all__' class Active_Project_View(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Customer_First_Name= models.CharField(max_length=255, blank = False) Customer_Last_Name = models.CharField(max_length=255, blank = False) Customer_Phone_Number = models.CharField(max_length=10, blank=True) Customer_Zip = models.CharField(max_length = 5, blank … -
django left outer join filter non-matching records
The goal is to find out if a Survey Response doesn't have current answers for all top level questions. This could be done by getting all top level questions for the Response, and then filter out the questions which don't have current answers. I can write this in SQL but is there a way I can implement this using django's QuerySet interface? Models class Survey(Model): ... class SurveySection(Model): survey = ForeignKey(Survey, related_name='survey_sections') class SurveyQuestion(Model): survey_section = ForeignKey(SurveyQuestion, related_name='survey_questions') parent = ForeignKey('self') #questions can be nested class SurveyResponse(Model): survey = ForeignKey(Survey, related_name='survey_responses') class SurveyAnswer(Model): survey_response = ForeignKey(SurveyResponse, related_name='survey_answers') survey_question = ForeignKey(SurveyQuestion, related_name='survey_answer') SQL This should find all the top-level questions for the Survey the Response is for, getting the current answers that match those questions and removing the questions that don't have answers. select * from survey_surveyquestion question join survey_surveysection section on section.id = question.survey_section_id join survey_survey survey on survey.id = section.survey_id join survey_surveyresponse response on response.survey_id = survey.id left outer join survey_surveyanswer answer on answer.survey_question_id = question.id and answer.is_current = true where response.id = 16 and answer.id is null and question.parent is null -
Is there any way to retrieve Objects from ManyToManyFields in the order they were added?
I have a bunch of Recipes and would like the User to have the option to save the ones he likes. I originally made it with a ManyToManyField on the Recipe model to to the User model but the problem was i wasn't getting them back in order that they were saved. Is there any way to do this? If not, what should i do instead to be able to keep the order? Make a third model with a date field and link the two? Seems like a bit of a waste. Any help would be nice. Thank you -
could not pass custom response
when I am querying for the job_seeker profile and If there is no job_seeker data then I was getting an error JobSeeker models query does not exist. I instead want to pass empty list if there is no data. For this, i tried the following way but i am getting an error so could not pass the custom response class JobSeekerNode(DjangoObjectType): class Meta: model = models.JobSeeker interfaces = (relay.Node, ) class JobSeekerQueries(ObjectType): job_seeker = Field(JobSeekerNode) def resolve_job_seeker(self, info, **kwargs): data = {} if info.context.user.is_authenticated: try: profile = Profile.objects.get(user=info.context.user) try: job_seeker = models.JobSeeker.objects.get(profile=profile) data['job_seeker'] = job_seeker except: # when there's no row instead of passing error, pass empty list data['job_seeker'] = [] return JsonResponse(data) except Profile.DoesNotExist: return [] return None this is the error i get when trying to pass the custom response(empty list if there's no data) { "errors": [ { "message": "Received incompatible instance \"<JsonResponse status_code=200, \"application/json\">\"." } ], "data": { "job_seeker": null } } -
Image upload in CreateView
I have a CreateView in my project to post a tweet-like-post. It has a title and content. It look like this in views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): # Author for post (required- if no- error) form.instance.author = self.request.user return super().form_valid(form) And I would like to add picture-upload column to make a persons able to upload a picture with the post. My models.py looks like this class Post(models.Model): title = models.CharField(max_length=100, verbose_name='タイトル') content = models.TextField(verbose_name='内容') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('Post-detail', kwargs={'pk': self.pk}) I already have a uploaded_pic folder in my static with 777 permision. Could you please tell me how to add there working picture-upload column -
Cannot access the Django server at http://127.0.0.1:8000/ after creating superuser
At the first time, it worked totally fine (impassion) Subinui-MacBook-Pro:3rd subin$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 20, 2019 - 01:42:24 Django version 2.2.2, using settings 'impassion_community.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [20/Jun/2019 01:42:50] "GET /admin HTTP/1.1" 301 0 [20/Jun/2019 01:42:50] "GET /admin/ HTTP/1.1" 302 0 [20/Jun/2019 01:42:50] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1819 [20/Jun/2019 01:42:50] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [20/Jun/2019 01:42:50] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17944 [20/Jun/2019 01:42:50] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [20/Jun/2019 01:42:50] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [20/Jun/2019 01:42:50] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [20/Jun/2019 01:42:50] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 Not Found: /favicon.ico [20/Jun/2019 01:42:50] "GET /favicon.ico HTTP/1.1" 404 1985 ^C(impassion) after it, I created the superuser Subinui-MacBook-Pro:3rd subin$ python3 manage.py createsuperuser Username (leave blank to use 'subin'): tnqls7378 Email address: tnqls7378@gmail.com Password: Password (again): Superuser created successfully. and tried to login, so I opened the chrome and connect to http://127.0.0.1:8000/admin/ again, but now I see the error message that I can't connect to the server anymore. what could possibly wrong? -
arcpy in django doesnot run
I have a script with ArcGIS using arcpy model. And I want to combine it with Django. The script runs on console successfully, however, when running with Django, I find the arcpy functions do not run. So I make a simple test for it, and get the same result. test.py import arcpy import os def test_arcpy(): tempFolder = arcpy.env.scratchFolder tempGDBPath = os.path.join(tempFolder, 'test.gdb') arcpy.env.overwriteOutput = True if not arcpy.Exists(tempGDBPath): arcpy.AddMessage('create..') arcpy.CreateFileGDB_management(tempFolder, 'test.gdb') return arcpy.Exists(tempGDBPath) views.py from django.http import HttpResponse from . import test def t(request): msg = str(test_arcpy()) return HttpResponse(msg) If I run the test.py in console, it return True.But if I run it in django, it always return false. If I cannot solve it , I cannot make more difficult script in django. Can you help me? I found the similar question in Flask app with ArcGIS, Arcpy does not run, but no solution in this question. -
How to upload docker django app to my vps
I am new in Django and docker and I finished my first docker's app with poqtgresql recently. Now I have a VPS with linux cent os. Please give me a source for full structure of how to Upload my app to my VPS.(I have no experience in server, so it can be great give me some info for configuration of server) -
How to fix 'No module named 'whitenoise'?
Django Version: 2.2.2 Exception Type: ModuleNotFoundError Exception Value: No module named 'whitenoise' Exception Location: in _find_and_load_unlocked, line 965 I from the local computer, put the project on a hosting, and such error got out '''''' CSS static doesn't work -
Function based view over CBV in django
I am very new to django. I am trying to learn django but i got confused which method i can choose between class-based views and function-based views.I personally find function-based views more easy than class-based views.Can i do it with only function-based views or class-based views is also very compulsory, so i can focus on the one more while moving forward to django. \ -
Get current item in Django list or template view
I’m trying to make a like button in Django . But in order for me to add the like , I will need to get the current item . I don’t won’t to have to go the the items detail view to get the current item , is there anyway I can get the current item in a list view. ? -
how to display web service data from a website and show it in HTML using Python?
I can't show this data in a table using Python, I just want to show this web service data in a table in an HTML file using Python. This is the web service data that I am trying to output into a table for viewing: {"returnCode":0,"message":null,"resultList":[{"poNo":"0000123456","deliveryDock":"D1","dcNo":"DC01","vendorNo":"0001112222","orderDate":"2019-06-07","deliveryDate":"2019-06-02","deliveryTime":"00:00","noOfPallets":"10.0000","source":"MANUAL","status":"Scheduled","auditList":[{"oldDeliveryDock":"D2","oldDeliveryDate":"2019-06-03","oldDeliveryTime":"01:30","changedBy":"XASNH","changedOn":"2019-06-07","reasonCode":"FCST"},{"oldDeliveryDock":"D3","oldDeliveryDate":"2019-06-04","oldDeliveryTime":"03:30","changedBy":"XRCA4","changedOn":"2019-06-07","reasonCode":"WOW"}]}]} I did a request like this in my views.py python page, but I am not sure how I would show this request in an HTML page def index(request): url = """http://53.01.187.244/Booking/getbookInfo?poNo=0000123456""" r = requests.get(url) data_dfs = pd.read_json(r.text) return render(request, 'users/index.html', {'data_dfs': data_dfs}) -
views.py and urls.py do not connect to perform a function
I have a mysql database connected to django, I know it is connected because you already showed me data. However I made a small form to do tests and does not save the data. The code is correct because I already moved it from place to def index (request): and there if you send me the data what is not because it does not enter correctly in the function that I did views.py from django.shortcuts import render, redirect from models import Test def index(request): test = Test.objects.all() context = {'test': test } return render(request, 'test_app/index.html', context) def create(request): print request.POST test = Test(name=request.POST['name'], breed= request.POST['breed']) test.save() return redirect('/') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^create/$', views.create) ] index.html <form action"/create" method="post"> {% csrf_token %} <label for="name">Name: <input type="text" name="name" /> </label> <label for="breed">Breed: <input type="text" name="breed"/> </label> <input type="submit" value="create" /> </form> I do not have an error just do not save in the database, in the console if you send a POST but without any variable. Use python 2.7 and django 1.1 -
Django model.field validators don't execute for required Boolean fields
My use case: I have a Yes/No question the user must answer, but they may answer it yes or no. I don't want to supply a default because I need the user to actively select their answer. If they do not select an answer, I want a form validation error, like "This field is required". I know that could store this in the DB as a CharField, but I'd prefer to store it as a required BooleanField. The issue appears to be that the form validation logic does NOT enforce required=True for Boolean fields, nor does it call the model field's custom validators when a value of '' is returned in the POST data. My setup: boolean_choices = ( (True, 'Yes'), (False, 'No'), ) def boolean_validator(value): if value is not True and value is not False: raise ValidationError("This field is required.") class Item(models.Model): accept = models.BooleanField( choices=boolean_choices, validators=[boolean_validator] ) class ItemForm(ModelForm): class Meta: model = Item fields = ['accept'] A complete, working demo of the issue is here: https://repl.it/@powderflask/django-model-form-validators Reproducing the issue create or edit an item, and set the 'accept' value to None ("-------") --> save will crash - notice form.is_valid() passed, crash is in form.save() --> notice that …