Friday, December 19, 2014

Model form with optional fields issue

Hello!

I have model form defined with all optional fields (required=False).
I want use this form to update only provided fields leaving others unchanged.
But Django replaces optional fields to empty values and removes data from models.


A short example:

class MyForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'email')

    def __init__(self, *args, **kw):
        super(MyForm, self).__init__(*args, **kw)
        for field in self.fields.values():
            field.required = False


In [21]: admin = User.objects.get(username='admin')

In [22]: admin.email
Out[22]: u'admin@example.com'

In [23]: form = MyForm(data={'username': 'admin'}, instance=admin)

In [24]: form.is_valid()
Out[24]: True

In [25]: form.save()
Out[25]: <User: admin>

In [26]: admin = User.objects.get(username='admin')

In [27]: admin.email
Out[27]: u''

In my opinion this is big, fat, ugly bug or a design misconception.  
If something is not provided does not mean that someting does not exist!
Django should skip updating these unprovided fields by removig them from cleaned_data dict. 

You can even try to save this form without data (ok with data, but with unknown keys):

form = MyForm(data={'unknownfield': 'some-value'}, instance=admin)
form.is_valid()

# form.cleaned_data has empty strings

form.save()


Username and email will be replaced with empty strings. 
Where is admin?, you'll ask... And you'll hear a strange voice - "admin is cooking borscht with ravioli, dude!"

What do you think - is this expected? 


/Marcin

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2d75eb34-1b5f-4cde-aba8-497802a3412a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment