python - 使用 django-allauth 在用户注册时创建用户和用户配置文件

标签 python django django-allauth

我正在使用 django-allauth 来处理帐户、登录、注销、注册,但我需要在创建时用户必须创建一个配置文件,并且我正在使用模型 UserProfile,因为它可以在代码中看到。问题是,当我创建自定义注册表单时,现在它会创建一个具有 [username, email, first_name, last_name, password] 的用户,但它不会创建 UserProfile。我有三个问题:

  1. 如何在注册时创建用户和用户配置文件?
  2. 如何为 django-allauth 附带的表单添加样式,即在/accounts/login/
  3. 我如何修改以便当用户登录时,它将他重定向到/profiles/而不是/accounts/profiles 或者根据 REST 原则将它设置为/accounts/profiles/如果是,那么是否可以修改配置文件应用程序,以便它可以使用 django-allauth View ?

我的自定义注册表单:

# django_project/profiles/forms.py
from django import forms
from allauth.account.forms import SignupForm
 
 
class CustomSignupForm(SignupForm):
    first_name = forms.CharField(max_length=30, label='First Name')
    last_name = forms.CharField(max_length=30, label='Last Name')
    bio = forms.CharField(max_length=255, label='Bio')
    def save(self, request):
        user = super(CustomSignupForm, self).save(request)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.bio = self.cleaned_data['bio']
        user.save()
        return user

设置:

# django_project/django_project/settings.py
ACCOUNT_FORMS = {
    'signup': 'profiles.forms.CustomSignupForm',
}

和主要的 url 模式:

# django_project/django_project/urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('profiles/', include('profiles.urls')),
    path('accounts/', include('allauth.urls')),
] 

个人资料应用中的 URL 模式:

# django_project/profiles/urls.py
app_name = 'profiles'
urlpatterns = [
    path('<str:user>/', ProfileView.as_view(), name='profile-detail'),
]

这是我的 ProfileView:

class ProfileView(LoginRequiredMixin, View):
    def get(self, request, user, *args, **kwargs):
        profile = UserProfile.objects.get(user=user)
        my_user = profile.user
        context = {
            'user': my_user,
            'profile': profile,
        }
        return render(request, 'profile/profile.html', context)

我的用户配置文件与 django 用户模型附带的用户模型不同:

User = settings.AUTH_USER_MODEL

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, verbose_name='user',
                                related_name='profile', on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, blank=True, null=True)
    last_name = models.CharField(max_length=30, blank=True, null=True)
    email = models.CharField(max_length=30, blank=True, null=True)
    bio = models.TextField(max_length=500, blank=True, null=True)

用户创建的信号:

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


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

最佳答案

如何在注册时创建用户和用户配置文件?

您可以在保存 CustomSignupForm 的同时创建一个 UserProfile

def save(self, request):
    user = super(CustomSignupForm, self).save(request)
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.bio = self.cleaned_data['bio']
    user.save()
    
    # Create your user profile
    UserProfile.objects.create(user=user, first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], email=self.cleaned_data['email'], bio=self.cleaned_data['bio'])

另一种优雅的方式是使用 Django signals在事件发生后执行一些操作,例如 user creation

信号.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import UserProfile

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        first_name = instance.first_name
        last_name = instance.last_name
        email = instance.email
        # The bio field is not set because the User instance has not bio attribute by default.
        # But you can still update this attribute with the profile detail form.
        UserProfile.objects.create(user=instance, first_name=first_name, last_name=last_name, email=email)

如果您想在每次更新用户时更新配置文件,请删除信号正文中的if created

apps.py

class AppNameConfig(AppConfig):
    
    # some code here

    # import your signal in the ready function
    def ready(self):
        import app_name.signals

关于python - 使用 django-allauth 在用户注册时创建用户和用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69990075/

相关文章:

python - 在分配律和交换律下找到等价结果

python - 将特征名称更新为 scikit TFIdfVectorizer

python - 相当于 Tornado 的阻塞?

django - 无法覆盖 django-allauth 模板

django - 将自定义用户模型与 django-allauth 一起使用会出现错误 Cannot resolve keyword 'username' into field。选择是 : activityhistory, app, ....,

python - 使用基于类的 View 将附加上下文变量数据传递到 allauth View 中

python - Django 错误 : Invalid column name 'id'

python - Django 与 mongodb 使用 pymongo 而不使用 ORM

database - Django : about external database model

Django Rest Framework 将额外的参数传递给 Serializer