【问题标题】:Add more field in SignupForm using django-allauth使用 django-allauth 在 SignupForm 中添加更多字段
【发布时间】:2020-01-20 13:27:07
【问题描述】:

型号:

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:这是我的项目名称。现在我改变它。
  • 所以all_authINSTALLED_APPS 中?
  • @dirkgroten:这是我的项目名称而不是应用程序名称。我在项目文件夹中创建 forms.py 和 models,py 。我还尝试创建应用程序并创建 forms.py 和 models,py 到应用程序。但在注册过程中查询未保存到配置文件模型中..
  • 您的所有模型都必须在已在 INSTALLED_APPS 中注册的应用中。

标签: django django-models django-forms django-allauth


【解决方案1】:

创建一个应用程序,比如accounts,有这段代码,但是创建完这段代码后才需要创建数据库,在项目中进行第一次迁移更准确

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)

【讨论】:

    猜你喜欢
    • 2016-03-26
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2013-08-11
    相关资源
    最近更新 更多