Django ModelForm is_valid & form_valid

1,065 views
Skip to first unread message

Jacob Valenta

unread,
Jun 20, 2013, 9:38:26 AM6/20/13
to django...@googlegroups.com
Basically, I have a model, a ModelForm, and an UpdateView. I go to the UpdateView (viewing a current customer) and just hit the submit button (changing no data). What results is an error from the model: Cannot assign None: "Customer.store" does not allow null values. (I do not have a field on the template for setting store, this should be handled and set to the users actie store) This error sounds like it is from the model being saved, which would mean that the form was valid (right?) Well I have tried using things like if form.is_valid() and def form_valid(self, form): but neither of those blocks of code ever execute. Out of desperation, I overrode the post method on the view, and made a form object, and passed it the instance and data. The page still returns the same error about Customer.store does not allow null values, But if form.is_valid() is in the error traceback.

Any help would be amazing!


models.py
class Customer(models.Model):
# Some fields that are not relevent

store = models.ForeignKey(Store, blank=True)

forms.py
class CustomerInformationForm(forms.ModelForm):
class Meta:
model = Customer
                 
views.py
class CustomerInformationView(UpdateView): 
template_name = "customers/customer_information.html 
model = Customer 
form_class = CustomerInformationForm
    
def form_valid(self, form): 
customer = form.save(commit=False)
customer.store = self.request.user.active_profile.store
customer.save() 
return super(CustomerInformationView, self).save(form)
        
def get_object(self, *args, **kwargs):
return Customer.objects.get(number=self.kwargs.get('customer_number'))  


Environment:


Request Method: POST

Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'mercury.core',
 'mercury.stores',
 'mercury.customers',
 'mercury.profiles',
 'django.contrib.admin',
 'south',
 'debug_toolbar')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'mercury.profiles.middleware.ActiveProfileMiddleware')


Traceback:
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  86.         return handler(request, *args, **kwargs)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  222.         return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  164.         if form.is_valid():
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  126.         return self.is_bound and not bool(self.errors)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  117.             self.full_clean()
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  274.         self._post_clean()
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
  315.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/forms/models.py" in construct_instance
  52.             f.save_form_data(instance, cleaned_data[f.name])
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in save_form_data
  466.         setattr(instance, self.name, data)
File "/Users/jacobvalenta/.virtualenvs/mercury/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
  401.                                 (instance._meta.object_name, self.field.name))

Exception Type: ValueError at /customers/1
Exception Value: Cannot assign None: "Customer.store" does not allow null values.

Jason Arnst-Goodrich

unread,
Jun 20, 2013, 12:27:36 PM6/20/13
to django...@googlegroups.com
This is a common problem to run into.

def form_valid(self, form): 
customer = form.save(commit=False)
customer.store = self.request.user.active_profile.store
customer.save() 
return super(CustomerInformationView, self).save(form)

super(CustomerInformationView, self).save(form)doesn't really make sense to do here for 2 reasons:

1. You just performed the model save manually the line above.
2. It's going to call save again except this time the form value for store is in fact Null (because it's blank in the form) and will raise the error.

So instead of calling super() - just return a httpresponse instead because that's really all you want in this case.
return HttpResponseRedirect(self.get_success_url())

(make sure you ahve the success url defined. Otherwise specify one.)

Also on your form you probably want to define it to exclude store - and if store is actually required you can probably leave off the blank=True.

Jacob Valenta

unread,
Jun 20, 2013, 4:58:44 PM6/20/13
to django...@googlegroups.com
Thank you good sir! You have put an end to my week long head ache!
Reply all
Reply to author
Forward
0 new messages