[Django]-Django admin action

5πŸ‘

βœ…

  1. Subclass UserAdmin, you can import it from django.contrib.auth.admin

  2. Add the action you added, use PasswordResetForm by reverse engineering the password_reset view.

  3. Unregister User from admin.site, admin.site.register(User)

  4. Register your subclass as the modeladmin for User

Here’s an example (thanks Chris Pratt for pushing the use of unregister/register):

from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.tokens import default_token_generator
from django.conf import settings
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class YourUserAdmin(UserAdmin):
    actions = list(UserAdmin.actions) + ['send_reset_password']

    def send_reset_password(modeladmin, request, queryset):
        for user in queryset:
            form = PasswordResetForm({'email': user.email})
            form.full_clean()
            form.save({
                'use_https': request.is_secure(),
                'token_generator': default_token_generator,
                'from_email': settings.DEFAULT_FROM_EMAIL,
                'email_template_name': 'registration/password_reset_email.html',
                'request': request
            })

admin.site.unregister(User)
admin.site.register(User, YourUserAdmin)
πŸ‘€jpic

Leave a comment