我有一个用户模型(由 Django 预定义)和一个通过外键连接的 UserProfile 模型。
我正在创建两个单独的模型表单,以在单个模板中用作某种注册表单。
模型.py
class UserProfile(models.Model):
# This field is required.
user = models.ForeignKey(User, unique=True, related_name="connector")
location = models.CharField(max_length=20, blank=True, null=True)
表单.py
class UserForm(ModelForm):
class Meta:
model = User
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
但是,当我加载页面并填写表单信息时,UserProfileForm 要求我选择/填写用户字段才能进行验证。
但是,这个“用户”是现在正在创建的用户,因此我无法选择“用户”,因为它尚未创建/仍在创建中。
我知道该用户字段具有 unique=true 属性,但有办法使该字段成为“可选”吗?
我的 View (如下)应该处理它,这样一旦创建了用户对象,我将把 UserProfile 的外键设置为这个新创建的用户对象(除非我在views.py中也做错了什么)。
View .py
@csrf_protect
def register(request):
if request.method == 'POST':
form1 = UserForm(request.POST)
form2 = UserProfileForm(request.POST)
if form1.is_valid() and form2.is_valid():
#create initial entry for user
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
#create entry for UserProfile (extension of new_user object)
profile = form2.save(commit = False)
profile.user = new_user
profile.save()
return HttpResponseRedirect("/books/")
else:
form1 = UserForm()
form2 = UserProfileForm()
c = {
'form1':form1,
'form2':form2,
}
c.update(csrf(request))
return render_to_response("registration/register.html", c)
最佳答案
那么你可以设置:
user = models.ForeignKey(User, unique=True, blank=True, null=True, related_name="connector")
这将使用户关系成为可选的,但我认为这不是您所需要的。相反,为什么不直接从 UserProfile
表单中删除 user
字段并手动分配它,而不是让用户完全看到下拉列表。那么就不会有验证错误。
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ("user", )
关于python - 如何在Django中将unique=true的外键设置为 "optional"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923991/