Yuiry Kozlenko
Yuiry Kozlenko

Reputation: 665

In Django 1.8, what does "USERNAME_FIELD" mean by authentication system?

I have been learning Django for a week, In order to implement authentication system, I have created models.py file as tutorials.

from django.db import models
from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):

    username = models.CharField('username', max_length = 10, unique = True, db_index = True)
    email = models.EmailField('email address', unique = True)
    joined = models.DateTimeField(auto_now_add = True)
    is_active = models.BoolenField(default = True)
    is_admin = models.BoolenField(default = False)

    USERNAME_FIELD = 'username'
    def __unicode__(self):
         return self.username

I understand what username, email, joined, is_active, is_admin means, but I can't understand why I use USERNAME_FIELD.

Is username created by models.CharField equal to the 'username' in USERNAME_FIELD?

Why do I have to create USERNAME_FIELD?

What does def __unicode__(self): function mean?

Upvotes: 1

Views: 2666

Answers (2)

FamousJameous
FamousJameous

Reputation: 1583

According to the docs, USERNAME_FIELD is:

A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames.

So, USERNAME_FIELD specifies which model field is going to be used as the username. If your application uses an email address instead of a username, you would configure that using USERNAME_FIELD.

The __unicode__(self) method returns a string representation of the object. Without it, any time you try to display an object it will look like: <User: User object>. As you have it now, displaying a User object will instead show the User's username. In the Django tutorial part 2 they use the __str__ method in conjunction with the @python_2_unicode_compatible decorator to make it work with Python 2. In Python 3 __str__ is the equivalent of __unicode__ in Python 2.

Upvotes: 4

Eugene Yarmash
Eugene Yarmash

Reputation: 149963

Check the documentation for your version of Django:

USERNAME_FIELD

A string describing the name of the field on the User model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition).

USERNAME_FIELD defaults to "username" so you can skip setting it in your custom user model if the default works for you.

You can read about __str__() and __unicode__() methods here.

Upvotes: 1

Related Questions