Modify django's username policy? - django

Django default admin authentication module disallows use of the \ char in usernames. How can I make it accept it?
It looks like it's possible to edit contrib/auth/models.py's username field's validator, but that won't do because it requires a change to django's base code.

You can use custom regex validators and a custom user model in order to achieve this. Be sure to set USERNAME_FIELD and REQUIRED_FIELDS in your model definition and AUTH_USER_MODEL in your settings.
custom_userprofile_app.models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer.'),
validators=[
validators.RegexValidator(r'^(.*)$',
_('Enter a valid username. '
'This value may contain any characters', 'invalid'),
validators.MinLengthValidator(5, 'Username must be at least 5 characters'),
],
error_messages={
'unique': _("A user with that username already exists."),
})
# The rest of your fields, etc
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','first_name','last_name']
settings.py
AUTH_USER_MODEL = 'custom_userprofile_app.User'

You can override django's default User model and then edit the regex validator.
You are just required to create a child class of base user model and then define a setting for that.
Read how to specify custom user model # django docs

Related

Where is django.contrib.auth.User defined in Django source code

In Django official guide, it reads:
Inside this django.contrib.auth model, there is a User class, who has following attributes (username, password, email, first_name, last_name).
When I check the source code in github, I did not find this definition in django.contrib.auth.
I can only see class AbstractBaseUser(models.Model): in django/contrib/auth/base_user.py on this link, and class User(AbstractUser): in django/contrib/auth/models.py in this webpage.
Q1: what does class models.User mean in above official document, it means User is a class under models.py ?
Q2: if above is right, then where User class get attributes such as username, email etc?
Q1: what does class models.User mean in above official document, it means User is a class under models.py?
In Django one refers to a model with the app_name.ModelName. So if you specify a model, this is implemented in the app_name/models.py, but since models are defined in the models.py file, it makes no sense to include that in the name of the model.
For example the default for the AUTH_USER_MODEL setting [Django-doc] is auth.User, since the name of the app is auth, and the name of the model is User.
Q2: if above is right, then where User class get attributes such as username, email etc?
Through inheritance. Indeed if we look at the source code of the models.py file [GitHub], we see:
class User(AbstractUser):
"""
Users within the Django authentication system are represented by this
model.
Username and password are required. Other fields are optional.
"""
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
and the AbstractUser model [GitHub] defines the fields for username, email, etc.:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
# …
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
first_name = models.CharField(_('first name'), max_length=150, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
# …
AbstractUser is an abstract model. This means that Django does not create a table for it. Models that inherit from an abstract table will thus inherit fields, methods, etc. and these fields will then be defined on the model that inherits from AbstractUser.

Handling JWT Authentication and Soft Deleted Users in Django Rest Framework

I'm trying to make a username available once a user deletes their account. By default the username is unique meaning the username won't be available even after the account is soft deleted.
This is, by default, the setup that comes with django out of the box.
class CustomUser(AbstractUser):
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[UnicodeUsernameValidator()],
error_messages={
'unique': _("A user with that username already exists."),
},
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
is_active is used here to mark a model as deleted.
So that I can be able to take advantage of UniqueConstraint and add a condition, I have to drop the uniqueness of the username.
class CustomUser(AbstractUser):
username = models.CharField(
_('username'),
max_length=150,
unique=False,
help_text=_('Required. 150 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[UnicodeUsernameValidator()],
error_messages={
'unique': _("A user with that username already exists."),
},
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
class Meta:
constraints = [
models.UniqueConstraint(
fields=['username'],
name='active_username_constraint',
condition=models.Q(is_active=True)
)
]
This works for registrations. After a user has deleted their account, the username can be re-used during registration. However, when a user logs in, the following error is raised.
MultipleObjectsReturned at /api/vdev/login/
get() returned more than one CustomUser -- it returned 2!
I'm trying to find out a way to check if a user is_active as part of the authentication process. Is there a way this can be done?
I'm guessing the error is raised when the authenticate is being called from the UserModel. Looking at the source code, the method calls get_by_natural_key from the user manager. Examining the source code for this method shows us where we need to make the change.
Hence, what you'll probably have to do is to create a custom user manager, inheriting from BaseUserManager and overriding get_by_natural_key.
class MyUserManager(BaseUserManager):
...
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD: username, "is_active": True})
Then in your custom user model, set your manager to this custom user manager:
class CustomUser(AbstractUser):
...
objects = MyUserManager()

Add to auth_user [duplicate]

This question already has answers here:
Extending the User model with custom fields in Django
(16 answers)
Closed 2 years ago.
I have this program that gets most of its data from the auth_user table one the django database. I don’t know how to add a new column to it and make it actually work since it doesn’t recognize it when I do. Does anybody know how you would add a column that can be used in auth_user table in the default django database.
I think this is a part that well documented on Django's documentation site. I guess you are trying to create custom user model. But I recommend you to extend user model. Extending default user model will provide you more flexibility. I hope these two links will enough. If not, please comment me about missing parts to cover.
You can override default user model or extend user model with OneToOneField relation to satisfy this requirement.
1. I'll show you how to do custom User Model.
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from core.util.validators import UnicodeUsernameValidator
from .manager import UserManager
class User(AbstractBaseUser, PermissionsMixin):
"""
Username, Email and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_(
'150 characters or fewer. Letters, digits and #/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
null=True,
default=None
)
email = models.EmailField(
_('email address'),
blank=False,
unique=True,
error_messages={
'unique': _("A user with that email address already exists."),
},
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_(
'Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
permissions = (
('user_permission', "User Permission"),
('admin_permission', "Admin Permission"),
)
This is like a copy of what they have in their User model. here, You can add new fields.
Make sure to register this in settings.py
AUTH_USER_MODEL = 'userapp.User'
you can access extra_fields like
user.extra_field
2. I'll show you how to extend using OneToOneField.
from django.contrib.auth import get_user_model
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
...
# Extra fields Here
then you can access the extra fields as
user.profile.extra_field

Django custom User model throwing SystemCheckError - The field 'username' clashes with the name 'username'

I'm writing a custom User model in Django, inheriting it from AbstractUser as is mentioned in the official Django tutorials. But this throws an error.
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
redditauth.RedditUser.username: (models.E006) The field 'username' clashes with the field 'username' from model 'redditauth.reddituser'.
Here is the code I wrote for the custom user model.
class RedditUser(AbstractUser):
username = models.CharField(unique=True, primary_key=True, validators=[validate_reddit_username], max_length=20)
token = models.CharField(max_length=256)
USERNAME_FIELD = username
REQUIRED_FIELDS = ['token']
def reddit(self):
with open('secret.json', 'r') as f:
secret = json.load(f)
return praw.Reddit(client_id=secret['client_id'], client_secret=secret['client_secret'],
refresh_token=self.token, user_agent='Plan-Reddit by /u/SkullTech101')
I have tried renaming it to something other than username, thinking that maybe there was already field named username in AbstractUser, but that didn't solve the problem.
As #Alasdair pointed out, I had to use a string, not a variable, when setting the value of USERNAME_FIELD.
So in my case it was
USERNAME_FIELD = 'username'

Create user inactive as default (is_active default False)

I have facebook authentication in my website which I use omab / django-social-auth
I want to redirect users to another website to make them fill their details. So I want to have users as inactive when they first authenticate with their facebook accounts, then after they complete the form I save them as active users.
I manipulated the django/contrib/auth/models.py under my enviroment as with is_active fields as default=False; but they are saved as active user
but still the same result, even I add a normal user from the admin panel. Is there something I am missing?
class User(models.Model):
"""
Users within the Django authentication system are represented by this
model.
Username and password are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'#/./+/-/_ characters'))
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('e-mail address'), blank=True)
password = models.CharField(_('password'), max_length=128)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=False,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without '
'explicitly assigning them.'))
last_login = models.DateTimeField(_('last login'), default=timezone.now)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text='Specific permissions for this user.')
objects = UserManager()
def create_user(self, username, email=None, password=None):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = UserManager.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=False, is_active=False, is_superuser=False,
last_login=now, date_joined=now)
user.set_password(password)
user.save(using=self._db)
return user
Avoid modifying built-ins. There are better ways to do things.
Like signals. Signals are awesome.
In this case, I'd attach to the pre_save signal of django.contrib.auth.models.User, and manually correct the is_active property of the model instance (if the object is new).
This way, you can add some logic to make sure you're properly marking a user as not active.
Because user's added within the Admin should probably be active, if the admin marks them as active.
jack_shed suggested signals, which helped me find the direction to take it. But there was still work from there to figure out how exactly to test and modify after receiving the signal.
Here's what worked for me.
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
#receiver(pre_save, sender=User)
def set_new_user_inactive(sender, instance, **kwargs):
if instance._state.adding is True:
print("Creating Inactive User")
instance.is_active = False
else:
print("Updating User Record")
This will catch the action of creating a user before the save occurs, then test if this instance state is "adding" or not. That differentiates between creating and updating a model instance.
If you don't do this test, updating the user sets is_active to False also, and there ends up being no way to activate them through django.
Elegant solution when using django-allauth.
There is another very nice solution.. one that sounds very much like what you desire.
I have created a custom form (in my case a ModelForm) that I can hand over to django-allauth via the ACCOUNT_SIGNUP_FORM_CLASS setting. What this does.. is ask the new potential user to supply additional fields during the signup process.
That has some very nice advantages:
You can add some fields very elegantly in addition to the default stuff.
It works for both social and "normal" signup.
No patching of 3rd party apps required.
You are still able to modify and maintain everything in the admin.
In the custom form you get access to the new user instance before it gets saved to the
database. This means you can even process the provided information do things like create a profile object for him and set the user as inactive ..all in one go.
This works because you can check if everything is ok.. and only then commit to do all these steps or reject the form with a validation error. :)
Well.. sounds good right?
But how exactly does it work (i.e. look like)?
I am glad you asked.. ^_^
For your use case it might look something like this:
settings.py
[...]
ACCOUNT_SIGNUP_FORM_CLASS = "<your_app>.forms.SignupForm"
[...]
forms.py
class SignupForm(forms.Form):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.is_active = False
user.save()
I think a better approach would be to customize your own model manager by leaving the user value inactive as default.
Create in your app: project_app/managers.py:
# project_app/managers.py
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_active', False)
return self._create_user(username, email, password, **extra_fields)
and in you models:
#project_app/models.py
from .managers import UserManager
from django.contrib.auth.models import AbstractUser
class UserManager(AbstractUser):
objects = UserManager()
# your custom fields go here.