我正在尝试制作一个包含注册/登录操作的webapp。登录工作正常,但注册表格令人沮丧。
我有一个继承自UserCreationForm的类注册表单。创建用户时会在管理页面中创建和查看用户,但我遇到的问题是无法在管理页面的UserProfile模型中看到它们。它没有链接信息,我找不到链接它们的方式。
以下是注册表格:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
city = forms.CharField(required=False)
country = forms.CharField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
username = forms.CharField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'country',
'city',
'email'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
#user.first_name = self.cleaned_data['first_name']
if commit:
user.save()
return user
以下是我的模特:
class UserProfile(models.Model):
user = models.OneToOneField( User,
on_delete=models.CASCADE
)
username = models.TextField(max_length=30, default="")
first_name = models.TextField(max_length=30, default="")
last_name = models.TextField(max_length=30, default="")
country = models.TextField(max_length=30, default="Which country are you from?")
city = models.TextField(max_length=30, default="Which city are you from?")
class ColorChoice(models.Model):
user = models.ForeignKey(
'UserProfile',
on_delete=models.CASCADE
)
color1 = models.IntegerField()
color2 = models.IntegerField()
color3 = models.IntegerField()
color4 = models.IntegerField()
color5 = models.IntegerField()
和我的view.py进行注册:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('color')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'account/create_new.html', args)
答案 0 :(得分:1)
您的form
仅为User
创建新对象。例如,您需要添加signal
来为UserProfile
创建新对象。
这样的事情:
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
signals.post_save.connect(create_user_profile, sender=User)