如何制作一个用户注册表单,其中包含一个模型字段作为必填字段?
就像我希望college
字段在注册页面上显示为下拉菜单
my models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
college = models.ForeignKey(College, on_delete=models.CASCADE)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
class College(models.Model):
col = models.CharField(max_length=100)
def __str__(self):
return self.col
my forms.py
class UserForm(UserCreationForm):
col = College.objects.all()
password1 = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)
college = forms.ChoiceField(widget=forms.Select(choices=col))
class Meta:
model = User
fields = ('username', 'college', 'password1', 'password2',)
并且views.py包含:
def signup(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = UserForm()
return render(request, 'registration_form.html', {'form': form})
更新
了解了ModelChoiceField并在forms.py中进行了这些更改:
class UserForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)
college = forms.ModelChoiceField(queryset=College.objects.all(), empty_label=None)
class Meta:
model = User
fields = ('username', 'college', 'password1', 'password2')
但所选择的大学没有保存在个人资料中
管理员部分也发出RelatedObjectDoesNotExist at /admin/login/
错误