Reputation: 589
So I have a modelform which I use with a modelformset factory.
If I leave the form class like this, I receive no error:
class CheckinForm(ModelForm):
class Meta:
model = Checkout
fields = ('return_date', )
def __init__(self, *args, **kwargs):
super(CheckinForm, self).__init__(*args, **kwargs)
self.fields['return_date'].widget = CheckboxInput()
If I add another field, extension
to thefields
, I get (1048, "Column 'book_id' cannot be null")
, BUT, the changes are saved to the database.
Here is my model:
class Checkout(models.Model):
book = models.ForeignKey(Book)
user = models.ForeignKey(User)
checkout_date = models.DateField(auto_now_add = True)
return_date = models.DateField(null = True, blank=True)
extension = models.IntegerField("Extension in days", blank = True, default = 0)
and here is the view that handles the form:
def checkin(request):
c = RequestContext(request, dictionary)
CheckinFormSet = modelformset_factory(Checkout, CheckinForm)
if request.method == "POST":
data = request.POST.copy()
for i in range(0, int(data['form-TOTAL_FORMS'])):
if 'form-' + str(i) + '-return_date' in data:
data['form-' + str(i) + '-return_date'] = datetime.date.today().isoformat()
else:
data['form-' + str(i) + '-return_date'] = ''
formset = CheckinFormSet(data = data)
user_form = AutoUserForm(data = data)
if formset.is_valid():
c['cool'] = 'cool'
formset.save()
else:
c['err'] = formset.errors
c['data'] = data
else:
CheckinFormSet = modelformset_factory(Checkout, CheckinForm)
user_form = AutoUserForm()
c['user_form'] = user_form
c['form'] = CheckinFormSet
c['context'] = 'checkin'
return render_to_response('lib_admin/checkin.html', {}, c)
I have to go through the form data because for the return_date
field I just have a checkbox that the user will tick, and it'll insert the current date.
This seems really weird to me, especially because the data is saved, even though I receive the IntegrityError.
Upvotes: 0
Views: 385
Reputation: 31951
It isn't a good idea to use blank=True
together with default
. It either has value (default) or not (blank), but not both in the same time.
Solution:
extension = models.IntegerField("Extension in days", default=0)
Upvotes: 1