Hi folks,
I am running into a validation problem with ModelForms - here is a quick
summary of what is happening
Take a simple model - here we call Model.full_clean as part of the custom save
method to enforce the validation:
from django.db import models
class Stuff(models.Model):
"""(Stuff description)"""
name = models.CharField(max_length=100)
age = models.IntegerField()
description = models.TextField(blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
self.full_clean()
return super(Stuff, self).save(*args, **kwargs)
Simple ModelForm for the above - nothing unusual here:
from django import forms
class StuffModelForm(forms.ModelForm):
class Meta:
model = Stuff
# Instantiate the form with some data
form = StuffModelForm({
'name': 'Fred',
'age': '56',
'description': 'Old Fred is 57',
})
# Check the form is valid
if form.is_valid():
obj = form.save(commit=False) # save but don't commit
obj.age = 27 # Change the age
obj.save() # Do a full save of the object
obj.name = 'Ted' # Change the name
obj.save() # Attempt to update the db record
# you get this error:
ValidationError: {'id': [u'Stuff with this ID already exists.']}
This happens because the ModelForm sets ModelForm.instance._adding to True and
never cleans it up. This is then tested for in Model._perform_unique_checks
and the uniqueness checks are executed if it is set to True which it always is
after calling ModelForm.save()
Is this a bug? Surely it can't be that unusal to want to call
Model.full_clean() before each save?
--
David Reynolds
[email protected]
--
You received this message because you are subscribed to the Google Groups
"Django developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-developers?hl=en.