使用 django-allauth 时如何自定义用户配置文件 [英] How to customize user profile when using django-allauth
问题描述
我有一个带有 django-allauth 应用程序的 django 项目.我需要在注册时从用户那里收集其他数据.我在这里遇到了一个类似的问题,但是不幸的是,没有人回答个人资料定制部分.
I have a django project with the django-allauth app. I need to collect additional data from the user at signup. I came across a similar question here but unfortunately, no one answered the profile customization part.
Per the documentation provided for django-allauth
:
一个指向自定义表单类(例如 ‘myapp.forms.SignupForm’
)的字符串,在注册期间用于要求用户提供其他输入(例如通讯注册、出生日期).这个类应该实现一个 ‘save’
方法,接受新注册的用户作为它的唯一参数.
ACCOUNT_SIGNUP_FORM_CLASS
(=None
)A string pointing to a custom form class (e.g.
‘myapp.forms.SignupForm’
) that is used during signup to ask the user for additional input (e.g. newsletter signup, birth date). This class should implement a‘save’
method, accepting the newly signed up user as its only parameter.
我是 Django 的新手,正在为此苦苦挣扎.有人可以提供此类自定义表单类的示例吗?我是否需要添加一个模型类以及指向用户对象的链接,例如 这个 ?
I am new to django and am struggling with this. Can someone provide an example of such a custom form class? Do I need to add a model class as well with a link to the user object like this ?
推荐答案
假设您想在注册时询问用户的名字/姓氏.您需要将这些字段放入您自己的表单中,如下所示:
Suppose you want to ask the user for his first/last name during signup. You'll need to put these fields in your own form, like so:
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()
然后,在您的设置中指向此表单:
Then, in your settings point to this form:
ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm'
请注意,SignupForm
不能与通过 ACCOUNT_FORMS
或 SOCIALACCOUNT_FORMS
覆盖的表单在同一文件中定义,因为这会导致循环导入错误.
Note that SignupForm
cannot be defined in the same file as form overrides through ACCOUNT_FORMS
or SOCIALACCOUNT_FORMS
, because that would lead to a circular import error.
仅此而已.
这篇关于使用 django-allauth 时如何自定义用户配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!