【问题标题】:Django Password Reset Confirm error (custom user model); updateDjango Password Reset Confirm 错误(自定义用户模型);更新
【发布时间】:2021-10-27 03:26:56
【问题描述】:

我没有编写 Python/后端的经验,但正在努力改进。在开发/本地服务器中,我正在尝试创建密码重置表单...但是从忘记密码的电子邮件中访问链接时出现以下错误-在此之前密码未保存:

init() 缺少 1 个必需的位置参数:'user'

forms.py(几乎从 Django 的表单中复制/粘贴;微小的变化)

class ResetPasswordForm(SetPasswordForm):
    error_messages = {
        'password_mismatch': static_textLanguage['page_user_passwordReset_alert_passwordNotMatch'],
        'password_empty': static_textLanguage['global_alert_mandatoryField'],
        'minimum_length': static_textLanguage['global_alert_minCharacters_password'],
    }
    new_password1 = forms.CharField(
        required=False,
        widget=forms.PasswordInput(attrs={
            'id': 'page_userPasswordReset_content_form_input_passwordA',
            'maxlength': '25',
            'class': 'global_component_input_box'
        }),
    )
    new_password2 = forms.CharField(
        required = False,
        widget=forms.PasswordInput(attrs={
            'id': 'page_userPasswordReset_content_form_input_passwordB',
            'maxlength': '25',
            'class': 'global_component_input_box'
        }),
    )
    
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ResetPasswordForm, self).__init__(user, *args, **kwargs)

    def clean_new_password1(self):
        password1 = self.cleaned_data.get('new_password1')
        if password1 == '' or password1 is None:
            raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty')
        elif len(password1) < 8:
            raise forms.ValidationError(self.error_messages['minimum_length'], code='password_too_short')
        return password1

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password2 == '' or password2 is None:
            raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty')
        if password1 and password2:
            if password1 != password2:
                raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch')
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):
        password = self.cleaned_data["new_password1"]
        self.user.set_password(password)
        if commit:
            self.user.save()
        return self.user

views.py

class UserPasswordResetView(auth_views.PasswordResetConfirmView):
    template_name = '../frontend/templates/frontend/templates.user/template.page_passwordReset.html'
    form_class = ResetPasswordForm
    post_reset_login = True
    success_url = reverse_lazy('page_userLoginPrivate')

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

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        if self.validlink:
            context.update({
                'validlink': True,
                'form': self.form_class(),
                'static_json_text': static_textLanguage,
                'static_json_textGlobal': static_textGlobal
            })
        else:
            context.update({
                'validlink': False,
                'form': None,
                'static_json_text': static_textLanguage, 
                'static_json_textGlobal': static_textGlobal
            })
        return context

template.html(为了本练习的目的,.html 被简化)

    <div class="wrapper_page_userPasswordReset">
        {% if validlink %}
            <form id="page_userPasswordReset_content_form" class="page_userPasswordReset_content_form" method="post" novalidate>
            {% csrf_token %}
                    <div class="global_component_input_box_container">
                            {{ form.new_password1}}
                    </div>
                    <div id="page_userPasswordReset_input_passwordA_alert_errors" class="alert_message_input_danger_format">
                        {% if form.errors %}
                            {% for key, value in form.errors.items %}
                                {% if key == 'new_password1' %}
                                    {{ value }}
                                {% endif %}
                            {% endfor %}
                        {% endif %}                                
                    </div>

                    <div class="global_component_input_box_container">
                        {{ form.new_password2}}
                    </div>
                    <div id="page_userPasswordReset_input_passwordB_alert_errors" class="alert_message_input_danger_format">
                        {% if form.errors %}
                            {% for key, value in form.errors.items %}
                                {% if key == 'new_password1' %}
                                    {{ value }}
                                {% endif %}
                            {% endfor %}
                        {% endif %}                                
                    </div>

                    <button type="submit" id="page_userPasswordReset_content_form_button_submit" class="global_component_button button_background_green">{{ static_json_text.global_button_submit }}</button>
            </form>
        {% else %}
            <a href="{% url 'password_reset' %}" class="is_link_color_black"><button id="page_userPasswordReset_button_forgotPassword" class="global_component_button button_background_green">{{ static_json_text.page_user_passwordReset_notValidLink_button }}</button></a>
        {% endif %}    
    </div>
django

【问题讨论】:

  • 你能分享完整的回溯吗?看起来您不需要编写 __init__,因为它与 SetPasswordForm 所做的事情相同
  • 您好@bdbd,感谢您的及时回复。回溯是什么意思?我不是经验丰富的 Python/Django 开发人员。最近开始。
  • @MarcosBenvenuto Traceback 显示错误发生的确切位置;见geeksforgeeks.org/python-traceback(这是谷歌搜索“python traceback”时的第一个链接之一)

标签: django django-views django-templates passwords


【解决方案1】:

该错误很可能发生,因为您将 user 定义为位置参数 (def __init__(self, user, *args, **kwargs):),但您将变量作为关键字参数 (kwargs['user'] = self.user) 传递。

代替你的代码:

class ResetPasswordForm(SetPasswordForm):
    ...

    def __init__(self, user, *args, **kwargs):
        self.user = user
        ...

尝试将其更改为此(以便ResetPasswordFormkwargs 中查找user):

class ResetPasswordForm(SetPasswordForm):
    ...

    def __init__(self, *args, **kwargs):
        self.user = kwargs['user']
        ...

【讨论】:

  • 您好@Ralf,感谢您的帮助,但我仍然收到与您的建议相同的错误。
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 2013-04-29
  • 2019-05-29
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多