Home > Software engineering >  Django Customize PasswordResetView: __init__() missing 1 required positional argument: 'user�
Django Customize PasswordResetView: __init__() missing 1 required positional argument: 'user�

Time:09-24

I try to customize Django PasswordResetView in order to validate the length of the password but I get this error:

TypeError at /accounts/password_reset/
__init__() missing 1 required positional argument: 'user'

views.py

from django.contrib.auth import views as auth_views

class PasswordResetView(auth_views.PasswordResetView):
    form_class = PasswordResetForm
    template_name = "accounts/users/password_reset.html"
    email_template_name = "accounts/users/password_reset_email.html"
    subject_template_name = "accounts/users/password_reset_subject.txt"
    from_email = settings.EMAIL_HOST_USER
    success_url = reverse_lazy("accounts_password_reset_done")

forms.py

from django.contrib.auth.forms import SetPasswordForm

class PasswordResetForm(SetPasswordForm):

    def clean_new_password1(self):
        password = self.cleaned_data.get("new_password1")
        if len(password) < 12:
            raise forms.ValidationError("Password must be at least 12 characters.")
        return password

It is obvious that SetPasswordForm class needs to be taken user upon initialization:

class SetPasswordForm(forms.Form):
   . . .
    
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super().__init__(*args, **kwargs)

I do not find a clear solution to how to pass user data to PasswordResetView and PasswordResetForm because user data is used upon PasswordResetForm instance creation.

CodePudding user response:

The SetPasswordForm is used in the PasswordResetConfirmView view, not the PasswordResetView. In the PasswordResetConfirmView, the get_form_kwargs() method [Django-doc] is overridden with [GitHub]:

def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['user'] = self.user
    return kwargs

You thus likely should subclass the PasswordResetConfirm view, and work with the PasswordResetForm form for the PasswordResetView.

  • Related