On Tue, Apr 1, 2014 at 4:19 PM, Claus Conrad <li...@clausconrad.com> wrote:

> Hi,
>
> sorry for the newbie question!
>
> In the admin I cannot create a user without a username, but on the shell
> it is possible:
>
> >>> from django.contrib.auth.models import User
> >>> u = User()
> >>> u.save()
> >>> u.id
> 2
>
> I am trying to understand why this is possible. Does this mean model
> constraints in general are not enforced when instances are created and
> saved? Thus I will always have to validate my models before saving them,
> unless I set null=True on a field, in which case I'd expect to get an
> exception?
>

It's possible to create an object like this because the object you
constructed is legal according to the model definition.

>>> u = User()
>>> print u.username
u''
>>> print u.first_name
u''
>>> print u.last_name
u''
>>> print u.is_staff
False
etc.

So - when you save the user, you're saving a completely legal user object -
with an empty username, first/last name, and default values for is_staff,
etc. If you try to create a *second* object the same way, you'll get an
error, because that would be a user with a duplicated username.

The admin does an additional set of checks. This is one area where there's
a leaky abstraction -- the "blank=True" definition on a model field is
actually form logic, not model logic. It isn't a data validation condition.
Admin uses this blank=True definition to determine if certain values should
be prohibited.

The reason for this is historical. Django's model validation framework came
quite late in the peace (around Django 1.2). For backwards compatibility
reasons, there are problems introducing model level validation on existing
models. The forms framework on the other hand, including blank=True,  has
been there since the beginning.

Yours,
Russ Magee %-)

-- 
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+unsubscr...@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/CAJxq849TOn8eygeegt2eUu4X330r363QHp%2BPbnpoCaEAZLETjA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to