如何覆盖django注册视图类

问题描述 投票:0回答:1

我想覆盖django all-auth注册视图以输入额外的字段值。

在这种情况下,用户模型具有外部字段,该字段与公司模​​型组合。

from allauth.account.views import SignupView as AllAuthSignupView
from .models import Company

class SignupView(AllAuthSignupView):
    def save(self):
        user = super(SignupView, self).save()
        a_company = get_object_or_404(Company, name='A')
        user.company = a_company

        return user

但是,这只保存用户名,密码和电子邮件。公司字段为NULL。我不想要一个建议更改公司模型中的默认值的答案。这不是我试图解决这个问题的方式。

django django-allauth class-based-views allauth
1个回答
0
投票

您可以简单地创建一个新表单来保存其他数据,而不是覆盖视图。例如:

companies = (
    ('comapny_name_1', 'ABC'),
    ('comapny_name_2', 'DEF'),
)


class SignupForm(forms.Form):
    company = forms.ChoiceField(choices=companies)

    def signup(self, request, user):
        user.company = Company.objects.get(name=self.cleaned_data['company'])
        user.save()

然后在ACCOUNT_SIGNUP_FORM_CLASS中添加表单路径到settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'path.to.SignupForm' 

更多信息可以在documentation找到。

© www.soinside.com 2019 - 2024. All rights reserved.