Создание пользователя и профиля пользователя при регистрации пользователя с помощью django-allauth
Я использую django-allauth для получения учетных записей, входа, выхода, регистрации, но мне нужно, чтобы при создании пользователь создавал профиль, и я использую модель UserProfile, как видно из кода. Проблема в том, что когда я создал пользовательскую форму регистрации, теперь она создает пользователя с [имя пользователя, email, имя_фамилия, фамилия, пароль], но не создает UserProfile. И у меня есть три вопроса:
- How to create a User and a UserProfile on signup?
- How can add styling to the forms that come with django-allauth, i.e. at /accounts /login/
- How can I modify so that when the user logs in, it will redirect him to /profiles/ instead of /accounts/profiles or is it better in terms of REST principles to have it /accounts/profiles/ if yes, then is it possible to modify the profiles app so that it can use django-allauth views?
Моя пользовательская форма регистрации:
# 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)
У меня профиль пользователя отличается от модели User, которая поставляется с django user model:
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)
Как создать пользователя и профиль пользователя при регистрации?
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, т.е. в
Создайте новый каталог в шаблонах, назовите его /account/login.html и перенесите туда вашу форму, добавьте стили следующим образом
это можно сделать многими способами
- используя https://pypi.org/project/django-bootstrap4/
- https://pypi.org/project/django-widget-tweaks/ .
- ручная визуализация полей https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html
Как я могу модифицировать приложение, чтобы при входе пользователя оно перенаправляло его на /profiles/ вместо /accounts/profiles или лучше с точки зрения принципов REST иметь /accounts/profiles/, если да, то возможно ли модифицировать приложение profiles так, чтобы оно могло использовать представления django-allauth?
перейдите в файлы настроек и добавьте следующее
LOGIN_REDIRECT_URL = "/profiles"
Вы можете проверить больше настроек здесь https://django-allauth.readthedocs.io/en/latest/configuration.html
Как создать пользователя и профиль пользователя при регистрации?
Вы можете создать UserProfile
одновременно с сохранением CustomSignupForm
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
.
signals.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