开发者

Django - Form validation error

开发者 https://www.devze.com 2022-12-30 20:22 出处:网络
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)

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消