Home > Net >  Where is `USERNAME_FIELD` defined in Django source code?
Where is `USERNAME_FIELD` defined in Django source code?

Time:03-02

I found below in Django source code

class AbstractBaseUser(models.Model):
    ...
        def get_username(self):
        """Return the username for this User."""
        return getattr(self, self.USERNAME_FIELD)
    ...

I searched out the whole Django source code, but did not find out where the USERNAME_FIELD was defined.

Can anyone help on this please ?

CodePudding user response:

https://github.com/django/django/blob/main/django/contrib/auth/models.py#L377 USERNAME_FIELD was defined in AbstractUser

CodePudding user response:

You can found USERNAME_FIELD in AuthenticationForm class of django which inherites forms.FORM class of Form Api.

It is also defined in models.py in AbstractUser class.

It is given in constructor method that is __init__() of AuthenticationForm.

From Django original Code:

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True}))
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}),
    )

    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super().__init__(*args, **kwargs)

        # Set the max length and label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        username_max_length = self.username_field.max_length or 254
        self.fields['username'].max_length = username_max_length
        self.fields['username'].widget.attrs['maxlength'] = username_max_length
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                raise self.get_invalid_login_error()
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user(self):
        return self.user_cache

    def get_invalid_login_error(self):
        return ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'username': self.username_field.verbose_name},
        )

Here focus on __init__() for get clearification about USERNAME_FIELD.

It is used for getting user field from User model or you can normally say for getting username.

You can find it in your local machine using below path:

C:\Users\Username\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\contrib\admin\forms.py.

Remember: AppData folder will only appear if you select hidden items.

  • Related