django-allauth-覆盖默认注册表单 [英] django-allauth - Overriding default signup form

查看:47
本文介绍了django-allauth-覆盖默认注册表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在allauth的自定义注册表单中使用了以下代码(在forms.py中):

I'm using this code (in forms.py) for my custom signup form for allauth:

class RegistrationForm(UserCreationForm):
    birth_date = forms.DateField(widget=extras.SelectDateWidget(years=BIRTH_DATE_YEARS))

    class Meta:
        model = get_user_model()
        fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'gender', 'birth_date', 'city', 'country')

我当然在settings.py中指定了 ACCOUNT_SIGNUP_FORM_CLASS 来指向此表单,它显示了我输入的字段.但是,即使提交 signup 方法,它也永远不会被调用,因此在提交时不起作用.我已经尝试过使用 save 进行保存,但仍然是相同的-会产生一个错误,即在创建用户并将其保存到数据库时,我自定义添加的字段之一为空.那么,实现此目标的正确代码是什么?

I have of course specified ACCOUNT_SIGNUP_FORM_CLASS in settings.py to point to this form and it displays the fields which I've put in it. However, it does not work on submission, even if I put signup method it never gets invoked. I've tried with the save but still it's the same - it raises an error that one of my custom added fields is blank while creating user and saving it to the database. So, what's the correct code for achieving this?

推荐答案

感谢 @rakwen 找到正确解决方案的人此处.我写了我的自定义适配器,并将其放在我的应用程序的adapters.py中:

I've made it thanks to @rakwen who has found the correct solution here. I wrote my custom adapter and put it in adapters.py in my app:

from allauth.account.adapter import DefaultAccountAdapter

class AccountAdapter(DefaultAccountAdapter):
    def save_user(self, request, user, form, commit=False):
        data = form.cleaned_data
        user.username = data['username']
        user.email = data['email']
        user.first_name = data['first_name']
        user.last_name = data['last_name']
        user.gender = data['gender']
        user.birth_date = data['birth_date']
        user.city = data['city']
        user.country = data['country']
        if 'password1' in data:
            user.set_password(data['password1'])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            user.save()
        return user

然后我在settings.py中指定 ACCOUNT_ADAPTER 指向该适配器,它终于开始工作了!

Then I've specified ACCOUNT_ADAPTER in settings.py to point to that adapter, and it finally started to work!

这篇关于django-allauth-覆盖默认注册表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆