我应该如何在django-allauth的注册表格中添加一个字段?文档vs堆栈溢出vs博客文章



似乎有多种方法可以将简单字段添加到django-allauth注册表单中。

从@danielfeldroy我看到了下面引用的内容。

# SpyBookSignupForm inherits from django-allauth's SignupForm
class SpyBookSignupForm(SignupForm):
# Specify a choice field that matches the choice field on our user model
type = d_forms.ChoiceField(choices=[("SPY", "Spy"), ("DRIVER", "Driver")])
# Override the init method
def __init__(self, *args, **kwargs):
# Call the init of the parent class
super().__init__(*args, **kwargs)
# Remove autofocus because it is in the wrong place
del self.fields["username"].widget.attrs["autofocus"]
# Put in custom signup logic
def custom_signup(self, request, user):
# Set the user's type from the form reponse
user.type = self.cleaned_data["type"]
# Save the user's type to their database record
user.save()

但是,在对来自https://github.com/pennersr/django-allauth/issues/826pennersr(django allauth的创始人(表示,我们所要做的就是:

class SignupForm(forms.Form):
first_name = forms.CharField(max_length=30, label='Voornaam')
last_name = forms.CharField(max_length=30, label='Achternaam')
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()

然后将ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm'添加到我的设置中。

请参阅:如何在使用django-allauth 时自定义用户配置文件

但在文档中,我们有这样的内容:https://django-allauth.readthedocs.io/en/latest/forms.html#signup-allauth帐户表单注册表单

我们在哪里做:

from allauth.account.forms import SignupForm
class MyCustomSignupForm(SignupForm):
def save(self, request):
# Ensure you call the parent class's save.
# .save() returns a User object.
user = super(MyCustomSignupForm, self).save(request)
# Add your own processing here.
# You must return the original result.
return user

我们将ACCOUNT_FORMS = {'signup': 'mysite.forms.MyCustomSignupForm'}ACCOUNT_FORMS = {'signup': 'mysite.forms.MyCustomSignupForm'}添加到设置文件中。

所以我的基本问题是,如果我们假设只想添加几个字段,哪个字段是正确的?

因为我有一个非常基本的设置,没有一种方法有效。

我接近于我们继承forms.Form的那个。嗯,我没有任何错误。但它实际上并没有保存输入。尽管我可以通过print()语句看到cleaned()的输入数据。

我真的很困惑,我希望有人能帮我找出最好的方法。

这是我的东西。

class CustomSignupForm(forms.Form):
opt_in = forms.BooleanField(label="Add me to the email list", help_text="Don't worry. We won't spam you.", initial=True, required=False)
def signup(self, request, user):
user.opt_in = self.cleaned_data['opt_in']
user.save

然后在设置中,我有ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.CustomSignupForm'

因此,如果这是您的代码,错误是您没有调用save方法,因为缺少括号:

class CustomSignupForm(forms.Form):
opt_in = forms.BooleanField(label="Add me to the email list", help_text="Don't worry. We won't spam you.", initial=True, required=False)
def signup(self, request, user):
user.opt_in = self.cleaned_data['opt_in']
user.save() # Note ()

这应该可以解决你的问题

最新更新