Changing password in Django Admin - python

I recently created the admin.py based in the Django Project Document:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser
But I really missed the functionality that allow the administrator the possibility to change the users passwords. How is possible to add this functionality? I just copied and pasted the code the is in the link above.
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from customauth.models import MyUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class MyUserAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
('Important dates', {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(MyUser, MyUserAdmin)
# ... and, since we're not using Django's builtin permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
[UPDATE - Added Information]
I changed the following information but I still seeing just the password (crypted) in a read-only field. How is possible to add a link to change the password?
fieldsets = (
('Permissions', {'fields': ('is_active', 'is_admin','password')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password')}
),
)

Put this in your UserChangeForm:
password = ReadOnlyPasswordHashField(label=("Password"),
help_text=("Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using this form."))

password = ReadOnlyPasswordHashField(label= ("Password"),
help_text= ("Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using this form."))
There is change in the href, for previous versions of django you can use
this form.
For django 1.9+
this form

I added this method to my UserAdmin class:
def save_model(self, request, obj, form, change):
# Override this to set the password to the value in the field if it's
# changed.
if obj.pk:
orig_obj = models.User.objects.get(pk=obj.pk)
if obj.password != orig_obj.password:
obj.set_password(obj.password)
else:
obj.set_password(obj.password)
obj.save()
You can the show the password field normally, but admins will only see the hashed password. If they alter it, the new value is then hashed and save.
This adds a single query to each time you save a user via the admin. It should generally not be an issue, since most systems don't have admins intensively editing users.

You can also do like this, in this way you just have to write over the field password and once you will save it, it will create the hash for it :
class UserModelAdmin(admin.ModelAdmin):
"""
User for overriding the normal user admin panel, and add the extra fields added to the user
"""
def save_model(self, request, obj, form, change):
user_database = User.objects.get(pk=obj.pk)
# Check firs the case in which the password is not encoded, then check in the case that the password is encode
if not (check_password(form.data['password'], user_database.password) or user_database.password == form.data['password']):
obj.password = make_password(obj.password)
else:
obj.password = user_database.password
super().save_model(request, obj, form, change)

You could also consider extending the UserAdmin this way:
from django.contrib import admin
from myapp.models import CustomUser
from django.contrib.auth.admin import UserAdmin
class CustomUserAdmin(UserAdmin):
list_display = []
admin.site.register(CustomUser, CustomUserAdmin)

For a django version independent solution you can reverse the url in the UserChangeForm.__init__ with something like:
from django.core.urlresolvers import reverse
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password'].help_text = (
"Raw passwords are not stored, so there is no way to see "
"this user's password, but you can <a href=\"%s\"> "
"<strong>Change the Password</strong> using this form</a>."
) % reverse_lazy('admin:auth_user_password_change', args=[self.instance.id])

('Permissions', {'fields': ('is_active', 'is_superuser',)}),

Just delete "password" input in your class form:
class MyUserChangeForm(forms.ModelForm):
# password = forms.CharField(label='Password', required=True, widget=forms.PasswordInput)
# password = ReadOnlyPasswordHashField()
class Meta:
model = CustomUser
fields = '__all__'
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
django 3.2.8

Related

Extending django.contrib.auth.User model

I'm using django.contrib.auth and I have a working login/registration system, however I want to extend my User model to have street address and phone number for registration purposes only, and I'm not sure how can I do that properly. What I have done works but feels wrong and I would like to know a proper way to do this.
I created accounts app and in models.py I have this:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
address = models.CharField(max_length=200)
address_number = models.CharField(max_length=20)
phone = models.CharField(max_length=20)
...then I registered that in admin.py:
from django.contrib import admin
from .models import User
admin.site.register(User)
...then in settings.py I added this line:
AUTH_USER_MODEL = 'accounts.User'
...and wherever I used django.contrib.auth.User, now I use accounts.models.User.
As I said, this works however it somehow feels wrong and it easily could be as this is my first time extending the User model. Why I think this is wrong? For one, Users has disappeared in admin from "Authentication and Authorization" and is instead under "Accounts" (as expected).
How can I accomplish this in a proper way?
#EDIT:
Here is my register form:
from django import forms
from accounts.models import User
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(max_length=200, help_text='Required')
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
class Meta:
model = User
fields = (
'username',
'email',
'first_name',
'last_name',
'address',
'address_number',
'phone'
)
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords do not match.')
return cd['password2']
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError(
'Please use another e-mail, that is already taken.')
return email

Custom User model fields (AbstractUser) not showing in django admin

I have extended User model for django, using AbstractUser method. The problem is, my custom fields do not show in django admin panel.
My models.py:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_bot_flag = models.BooleanField(default=False)
My admin.py:
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
Thanks
If all you want to do is add new fields to the standard edit form (not creation), there's a simpler solution than the one presented above.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
class CustomUserAdmin(UserAdmin):
fieldsets = (
*UserAdmin.fieldsets, # original form fieldsets, expanded
( # new fieldset added on to the bottom
'Custom Field Heading', # group heading of your choice; set to None for a blank space instead of a header
{
'fields': (
'is_bot_flag',
),
},
),
)
admin.site.register(User, CustomUserAdmin)
This takes the base fieldsets, expands them, and adds the new one to the bottom of the form. You can also use the new CustomUserAdmin class to alter other properties of the model admin, like list_display, list_filter, or filter_horizontal. The same expand-append method applies.
You have to override UserAdmin as well, if you want to see your custom fields. There is an example here in the documentation.
You have to create the form for creating (and also changing) user data and override UserAdmin. Form for creating user would be:
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = '__all__'
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
You override UserAdmin with:
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
class UserAdmin(BaseUserAdmin):
add_form = UserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', 'is_bot_flag', 'password1', 'password2')}
),
)
and then you register:
admin.site.register(User, UserAdmin)
I pretty much copy/pasted this from documentation and deleted some code to make it shorter. Go to the documentation to see the full example, including example code for changing user data.
The quickest way to show your extra fields in the Django Admin panel for an AbstractUser model is to unpack the UserAdmin.fieldsets tuple to a list in your admin.py, then edit to insert your field/s in the relevant section and repack as a tuple (see below).
Add this code in admin.py of your Django app
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
fields = list(UserAdmin.fieldsets)
fields[0] = (None, {'fields': ('username', 'password', 'is_bot_flag')})
UserAdmin.fieldsets = tuple(fields)
admin.site.register(User, UserAdmin)
Note:
list(UserAdmin.fieldsets) gives the following list:
[ (None, {'fields': ('username', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name', 'email')}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups',
'user_permissions')}),
('Important dates', {'fields': ('last_login', 'date_joined')})
]
These fields are by default in Django user models, and here we are modifying the first index of the list to add our custom fields.
Try this...
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
phone_number = models.CharField(max_length=12)
settings.py : Add below line of code in settings.py
AUTH_USER_MODEL = 'users.CustomUser'
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = '__all__'
admin.py
from django.contrib import admin
from .models import CustomUser
from .forms import CustomUserCreationForm
from django.contrib.auth.admin import UserAdmin
# Register your models here.
class CustomUserAdmin(UserAdmin):
model = CustomUser
add_form = CustomUserCreationForm
fieldsets = (
*UserAdmin.fieldsets,
(
'Other Personal info',
{
'fields': (
'phone_number',
)
}
)
)
admin.site.register(CustomUser, CustomUserAdmin)
After all are done then run below command in terminal
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Django Custom Authentication - BaseUserManager's create_user not being used

I customizes Django's authentication and now every time I try to create a new user using Django Admin this user's password is saved directly, without being hashed. I found out that create_user method from BaseUserManager class is not being called. When I create a superuser using bash it is done properly. Is there anything wrong with my model?
settings.py
AUTH_USER_MODEL = 'authentication.BaseAccount'
apps/authentication/models.py
class BaseAccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError('Users must have a valid email address.')
account = self.model(
email=self.normalize_email(email)
)
account.set_password(password)
account.save()
return account
def create_superuser(self, email, password, **kwargs):
account = self.create_user(email, password, **kwargs)
account.is_admin = True
account.is_staff = True
account.save()
return account
class BaseAccount(AbstractBaseUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = BaseAccountManager()
USERNAME_FIELD = 'email'
def __unicode__(self):
return self.email
def get_full_name(self):
return ' '.join([self.first_name, self.last_name])
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
For future readers, because this issue also got me banging my head against the wall...
To access that precious create_user() method from anywhere in your django project :
from django.contrib.auth import get_user_model
class SomeClass():
# This could be a form, for example...
def some_function():
get_user_model().objects.create_user()
If you call it from the save() method of some custom form, please take proper care of the commit parameter, and don't forget to register your custom user model in the settings.py file, as per the Django documentation.
I found an answer to your question about passwords, but I still don't know how to get the create_user function to be called correctly. The example removes username in favor of just an email. I am still looking for a way to hit the create_user function defined in the custom UserManager inerhiting from BaseUserManager. My custom manager sends an email with a password reset link and a one time token... which would avoid the need to actually set a hashed password from django admin.
https://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/
first create your own forms:
# appname/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from appname.models import CustomUser
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and
password.
"""
def __init__(self, *args, **kargs):
super(CustomUserCreationForm, self).__init__(*args, **kargs)
del self.fields['username']
class Meta:
model = CustomUser
fields = ("email",)
class CustomUserChangeForm(UserChangeForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
def __init__(self, *args, **kargs):
super(CustomUserChangeForm, self).__init__(*args, **kargs)
del self.fields['username']
class Meta:
model = CustomUser
then use those forms:
# appname/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from appname.models import CustomUser
from appname.forms import CustomUserChangeForm, CustomUserCreationForm
class CustomUserAdmin(UserAdmin):
# The forms to add and change user instances
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference the removed 'username' field
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
form = CustomUserChangeForm
add_form = CustomUserCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
admin.site.register(CustomUser, CustomUserAdmin)

Updating Custom User Model in Django with Class Based UpdateView

I am using Django 1.7.1 with Python 3.4. I created a custom user model and now I have a need for users to be able to update their details. What I need is that, when users go to the form to update their details, the form is pre-populated with their data i.e. username, email and so on. So far, the form is showing but not with the current user data.
I have the following code:
models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
... # Some code left out for brevity
class AuthUser(AbstractBaseUser, PermissionsMixin):
"""
A fully featured User model with admin-compliant permissions that uses
a full-length email field as the username.
Email 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'),
validators=[validators.RegexValidator(re.compile('^[\w.#+-]+$'), _('Enter a valid username.'), _('invalid'))])
email = models.EmailField(_('email address'), max_length=254, unique=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)
objects = AuthUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username'] # Not needed since it has been mentioned in USERNAME_FIELD and is required by default and cannot be listed in REQUIRED_FIELDS
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_absolute_url(self):
return "/users/%s/" % urlquote(self.username)
def __str__(self):
return self.username
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their username
return self.username
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
forms.py
from django.contrib.auth.forms import UserChangeForm
from .models import AuthUser
class AuthUserChangeForm(UserChangeForm):
"""
A form for updating users. Includes all the fields on the user, but
replaces the password field with admin's password hash display field.
"""
password = ReadOnlyPasswordHashField(label="password",
help_text="""Raw passwords are not stored, so there is no way to see this
user's password, but you can change the password using <a href=\"password/\">
this form</a>""")
class Meta:
model = AuthUser
fields = ('username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions')
widgets = {
'email': TextInput(),
}
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the field does
# not have access to the initial value
return self.initial["password"]
views.py
class UpdateUserView(LoginRequiredMixin, FormView):
template_name = 'users/update_user.html'
form_class = AuthUserChangeForm
# get current user object
def get_object(self, queryset=None):
return self.request.user
urls.py
url(r'^profile/update/', UpdateUserView.as_view(), name='update_profile'),
What I'm I missing?
FormView is not the appropriate base class here: it doesn't know about model forms and doesn't define a get_object method. Use UpdateView instead.

Django: Add another field to django-registration

I am pretty new to django and I am very lost with django-registration. At the moment I have the django-registration set up an going but I need to add another field to it for a phone number. I need the phone number field in the registration field instead so I can use the api from twilio to send a verification link through text instead of email. How would I go about adding this one field to django-registration?
I work with django at work and for that kind of issue we used to attach a model to the user, example:
You create a new model, for example profile with a OneToOneField to user
Add your desired fields to that profile model, such as (tlf, country, language,log...)
Create admin.py to manage this model (profile) at the same time you manage users in django admin
Profile Model Example
class Profile(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(max_length=255, blank=True, null=True, verbose_name='phone')
description = models.TextField(blank=True, verbose_name='descripction')
...
...
class Meta:
ordering = ['user']
verbose_name = 'user'
verbose_name_plural = 'users'
admin.py example
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
filter_horizontal = ['filter fields'] # example: ['tlf', 'country',...]
verbose_name_plural = 'profiles'
fk_name = 'user'
class UserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
admin.site.unregister(User) # Unregister user to add new inline ProfileInline
admin.site.register(User, UserAdmin) # Register User with this inline profile
Create an user and attach a profile to him
# Create user
username = 'TestUser'
email = 'test#example.com'
passw = '1234'
new_user = User.objects.create_user(username, email, passw)
# Create profile
phone = '654654654'
desc = 'Test user profile'
new_profile = Profile(user=new_user, phone = phone, description=desc)
new_profile.profile_role = new_u_prole
new_profile.user = new_user
# Save profile and user
new_profile.save()
new_user.save()
Now you'll have this Profile model attached to each user, and you could add the fields you wish to Profile Model, and for example if you make:
user = User.objects.get(id=1)
you can access to his profile doing:
user.profile
and to access phone
user.profile.phone
Not django-registration, but I customized django-userena once to add a custom field to the signup form.
You can view the code here.
I am sure the process works more or less the same in django-registration too: overriding the signup form and adding custom fields.
However, django-registration is no longer maintained, I believe. It is a classic and works so well, but there are other options too.

Categories