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

问题描述 投票:0回答:3

我正在使用 django-allauth 来获取帐户、登录、注销、注册,但我需要在创建时用户必须创建一个配置文件,并且我正在使用模型 UserProfile,因为它可以在代码中看到。问题是,当我创建自定义注册表单时,它现在创建一个具有 [用户名、电子邮件、名字、姓氏、密码] 的用户,但它不会创建用户配置文件。我有三个问题:

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

我的自定义注册表单:

# 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'),
]

这是我的个人资料视图:

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()
python django django-allauth
3个回答
3
投票

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

您可以在保存

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 信号 在事件发生后执行一些操作,如

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

1
投票

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

 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):
        # create user the create profile
        user = super(CustomSignupForm, self).save(request)
        ### now save your profile 
        profile = UserProfile.objects.get_or_create(user=user)
        profile.first_name = self.cleaned_data['first_name']
        profile.last_name = self.cleaned_data['last_name']
        profile.bio = self.cleaned_data['bio']
        profile.save()
        return user

如何向 django-allauth 附带的表单添加样式,即 at

在模板中创建一个新目录,将其命名为 /account/login.html 并在那里渲染表单并添加样式,如下所示

这可以通过多种方式完成

  1. 使用https://pypi.org/project/django-bootstrap4/
  2. https://pypi.org/project/django-widget-tweaks/
  3. 手动渲染字段https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html

我该如何修改,以便当用户登录时,将他重定向到 /profiles/ 而不是 /accounts/profiles ,或者就 REST 原则而言,将其设置为 /accounts/profiles/ 如果是,那么是吗?可以修改配置文件应用程序以便它可以使用 django-allauth 视图吗?

转到您的设置文件并添加以下内容

LOGIN_REDIRECT_URL = "/profiles"

您可以在此处查看更多设置 https://django-allauth.readthedocs.io/en/latest/configuration.html


0
投票

您可以挂钩到 allauth.account.signals.user_signed_up(request, user) signal。添加到 models.py 中,其中描述了 UserProfile 类:

from allauth.account.signals import user_signed_up
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver

@receiver(user_signed_up)
def create_user_profile(request, user, **kwargs):
    UserProfile.objects.create(user=user)
© www.soinside.com 2019 - 2024. All rights reserved.