使用django-allauth在注册表单中添加更多字段

4

模型:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    nationality = models.CharField(max_length=20)

    def __str__(self):
        return self.user.first_name

    @receiver(post_save, sender=User)
    def create_user_profile(self, sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(self, sender, instance, **kwargs):
        instance.profile.save()

表单:

from allauth.account.forms import SignupForm

class CustomSignupForm(SignupForm):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)

    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'nationality', 'bio')

    def signup(self, request, user):
        # Save your user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        user.profile.nationality = self.cleaned_data['nationality']
        user.profile.gender = self.cleaned_data['bio']
        user.profile.save()

视图:

ACCOUNT_FORMS = {'signup': 'myproject.forms.CustomSignupForm',}

这个过程没有成功。 错误是:模型类all_auth.models.Profile没有声明一个明确的app_label并且不在INSTALLED_APPS中的应用程序中。

我该如何解决它?或者,我如何使用django-allauth添加更多字段到SignupForm?


难道不是 allauth 而不是 all_auth 吗? - dirkgroten
@dirkgroten:这是我的项目名称。现在我已经更改了它。 - jhon arab
所以 all_authINSTALLED_APPS 中吗? - dirkgroten
@dirkgroten:这是我的项目名称,而不是应用程序名称。我在项目文件夹中创建了forms.py和models.py。我还尝试创建应用程序并将forms.py和models.py创建到应用程序中。但是,在注册过程中,查询未保存到Profile模型中。 - jhon arab
我认为你应该使用save函数,而不是signup。 请参考此链接 https://django-allauth.readthedocs.io/en/latest/forms.html#signup-allauth-account-forms-signupform - aijogja
显示剩余3条评论
1个回答

6

创建一个应用程序,例如账户,其中包含这段代码,但是只有在创建此代码后才需要创建数据库,在项目中执行第一次迁移会更加准确。

accounts/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    phone = models.CharField(max_length=12)


accounts/forms.py

from allauth.account.forms import SignupForm
from django import forms
from .models import *

class SimpleSignupForm(SignupForm):
    phone = forms.CharField(max_length=12, label='Телефон')
    def save(self, request):
        user = super(SimpleSignupForm, self).save(request)
        user.phone = self.cleaned_data['phone']
        user.save()
        return user


settings.py
...
ACCOUNT_FORMS = {'signup': 'accounts.forms.SimpleSignupForm'}
AUTH_USER_MODEL = 'accounts.CustomUser'


accounts/admin.py

from django.contrib import admin
from .models import *

admin.site.register(CustomUser)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接