Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Form validation error

I have a model like this:

class Entity(models.Model):    
    entity_name = models.CharField(max_length=100)
    entity_id = models.CharField(max_length=30, primary_key=True)
    entity_parent = models.CharField(max_length=100, null=True)
    photo_id = models.CharField(max_length=100, null=True)
    username = models.CharField(max_length=100, null=True)
    date_matched_on = models.CharField(max_length=100, null=True)
    status = models.CharField(max_length=30, default="Checked In")

    def __unicode__(self):
        return self.entity_name

    class Meta:
        app_label = 'match'
        ordering = ('entity_name','date_matched_on')
        verbose_name_plural='Entities'

I also have a view like this:

def photo_match(request):
''' performs an update in the db when a user chooses a photo '''

    form = EntityForm(request.POST)
    form.save()

And my EntityForm looks like this:

class EntityForm(ModelForm):
    class Meta:
        model = Entity

My template's form returns a POST back to the view with the following values:
{u'username': [u'admin'], u'entity_parent': [u'PERSON'], u'entity_id': [u'152097'], u'photo_id': [u'2200734'], u'entity_name': [u'A.J. McLean'], u'status': [u'Checked Out'], u'date_matched_on': [u'5/20/2010 10:57 AM']}

And form.save() throws this error:

Exception in photo_match: The Entity could not be changed because the data didn't validate.

I have been trying to figure out why this is happening, but cannot pinpoint the exact problem. I can change my Entities in the admin interface just fine. If anybody has a clue about this I would greatly appreciate it!

Thanks, Igor

like image 612
IgorGanapolsky Avatar asked Apr 11 '26 05:04

IgorGanapolsky


1 Answers

If the entity you are trying to update is already saved, then you need to provide an instance parameter when you bind the form, otherwise save will try to perform an INSERT rather than an UPDATE, and the new object won't validate (check out the django docs here).

Try:

def photo_match(request):
''' performs an update in the db when a user chooses a photo '''

    entity = Entity.objects.get(pk=request.POST['entity_id'])
    form = EntityForm(request.POST, instance=entity)
    form.save()

You'll want to be a little more robust about the way you look up the entity, of course.

like image 160
meshantz Avatar answered Apr 13 '26 08:04

meshantz