我要在用户注册后自动创建用户个人资料。 请有人帮助我,我是Django的新手。 预先感谢。
我的代码文件包含以下内容:
models.py
:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import time
import os
from django.utils import timezone
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name='user')
slug = models.SlugField(blank=True, unique=True, null=True)
email_verified = models.BooleanField(default=False, null=True)
contact = models.CharField(max_length=14, blank=True, null=True)
gender = models.CharField(choices=GENDER_CHOICES, default='SELECT', max_length=15, null=True)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
about = models.TextField(null=True, blank=True, max_length=150)
updated_at = models.DateTimeField(auto_now=True, null=True)
def user_profile_pre_save_receiver(sender, instance, *args, **kwargs):
UserProfile.objects.get_or_create(user=instance)
pre_save.connect(user_profile_pre_save_receiver, sender=User)
forms.py
:
from allauth.account.forms import SignupForm
from django import forms
from django.contrib.auth.models import User
from . import models
class CustomSignupForm(SignupForm):
first_name = forms.CharField(max_length=40, label="First Name:", required=False, widget=forms.TextInput(
attrs={'placeholder':
('First Name'),
'autofocus': 'autofocus'}))
last_name = forms.CharField(max_length=40, label="Last Name:", required=False, widget=forms.TextInput(
attrs={'placeholder':
('Last Name'),
'autofocus': 'autofocus'}))
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
user.profile.save()
Settings.py
ACCOUNT_FORMS = {
'signup': 'accounts.forms.CustomSignupForm'
}