[Answered ]-Random password generation when admin creates employees in admin site

1👍

Solved by overwriting the ModelAdmin subclass’ save_model method.
Docs: Django ModelAdmin save_model. To make it reusable I just put it as a mixin.

class RandomPasswordAndEmailMixin:
    def save_model(self, request, obj, form, change):
        if not form.instance.pk:
            user = form.save(commit=False) 
            user.set_password(User.objects.make_random_password(20))
            user.save() 
            form.save_m2m()

        super().save_model(request, obj, form, change)

@admin.register(Employee)        
class EmployeeModelAdmin(RandomPasswordAndEmailMixin,admin.ModelAdmin):
    exclude = ('is_staff', 'password')

    

0👍

Try to fix the else clause to super().save(commit).

👤greg

Leave a comment