I will best explain what I mean with an example. 

Lets say we have a simple model called Book.

class Book(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=255)

    class Meta:
        unique_together = ('user', 'name')

so `Books` are linked to users, and we have added an unique constrain 
because we don't want a user to have the same book twice. 

Now lets say we want to allow users to create/update books, when we do this 
we would only need their book.name, we already knew who they are in the 
system.
So a simple ModelForm would look like this:

class BookForm(forms.ModelForm):
    class Meta:
         model = Book
         fields = ('name',)

Now since i've omitted the `user` field and I can't have a book w/o a user, 
its my responsibility to populate it. Thus when I create new form i will 
always a pass an instance with a user.
But before we do this, lets manually create 1 book for this user.

user = User.objects.get(pk=1)
book1 = Book.objects.create(user=user, name='Harry Potter')

#now lets build our form
book2 = Book(user=user)
form = BookForm(data={'name': 'Harry Potter'}, instance=book2)

if form.is_valid(): #yes the form will be valid
    book2 = form.save() #IntegrityError will be raised with UNIQUE 
constraint failed

Now this happens because `ModelForm.validate_unique 
<https://github.com/django/django/blob/1.8.18/django/forms/models.py#L434>` 
collects a set of fields to pass as an exclude fields into 
`instance.validate_unique`. 

Please, can someone explain me why is this done in such a manner, and what 
will be the correct way approach this problem.

>From my point of view when I define a ModelForm I imagine that I have to 
only explain what the user needs to see when the form gets rendered.
But when the instance is being validated, I would always want to validate 
this instance as a whole (with the fields that I've omitted).



-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/e5e49072-9d33-4faf-99f7-f7339437c73a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to