python - 将函数重写为类

标签 python django forms

我有一个更改用户密码的函数,现在我想将其重写到类 View 中,它给了我一个错误:

__init__() missing 1 required positional argument: 'user'

功能:

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, 'Your password was successfully updated!')
            return redirect('profile')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'accounts/change_password.html', {
        'form': form
    })

到目前为止的类 View

class ChangePasswordView(FormValidMessageMixin, FormInvalidMessageMixin, FormView):
    form_class = PasswordChangeForm
    template_name = 'accounts/change_password.html'
    success_url = reverse_lazy('profile')

    def get_form_valid_message(self):
        return 'Your password was successfully updated!'

    def get_form_invalid_message(self):
        return 'Please correct the error below.'

    def form_valid(self, form):
        form.author = self.request.user
        form.save()
        return super().form_valid(form)

url.py

path('change-password/', ChangePasswordView.as_view(), name='change-password'),

最佳答案

我假设您的表单需要一个参数user。因此,您需要在表单 View 中重写 get_form_kwargs() 方法来传递它,如下所示:

class ChangePasswordView(FormValidMessageMixin, FormInvalidMessageMixin, FormView):
    form_class = PasswordChangeForm
    # rest of the code
    def get_form_kwargs(self, *args, **kwargs):
       form_kwargs = super().get_form_kwargs(*args, **kwargs)
       form_kwargs['user'] = self.request.user
       return form_kwargs

关于python - 将函数重写为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56067749/

相关文章:

sql - 类似 Twitter 的帖子时间轴的数据库结构和查询

django - 你如何过滤 Django Rest Framework 中的嵌套序列化程序?

Django:在模板中显示带有前缀的表单名称

php - 添加更多(组)字段以通过 jQuery 形成

python - 获取属性错误: module 'django.db.models' has no attribute 'UniqueConstraint' in Django 1. 11

php - GET 有效但 POST 在 PHPStorm 中无效

python - 在tensorflow python中替换值或创建张量掩码

python - SQLAlchemy - 选择更新示例

python - 奇怪的字典调用?

python - 在 Multiprocessing python 中无法访问全局变量