保存模型表单时出现了一个奇怪的问题。我有一个表单,它由两个模型表单组成,我试图同时保存它们。为清楚起见,下面是我的代码
Views.py
def create_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
my_user_form = MyUsersForm(request.POST)
if user_form.is_valid() and my_user_form.is_valid():
us = user_form.save()
my_us = my_user_form.save(commit=False)
my_us.user = us
my_us.save()
return HttpResponse('You have successfully created a user')
else:
return HttpResponse(' My_user_form is not validated')
else:
user_form = UserForm()
my_user_form = MyUsersForm(user=request.user)
return render(request, 'create_user.html', {'user_form': user_form, 'my_user_form': my_user_form})
当我覆盖MyUsersForm的 init 方法来过滤外键的查询集(created_by)时,我没有验证my_user_form,但是当我不过滤查询集时,my_user_form被验证并且表单是保存。
我不明白的是,当我不过滤查询集时,my_user_form的验证方式是什么?
通过request.post发送到my_user_form的数据以某种方式丢失(当我过滤查询集时)。我们非常感谢任何正确方向的线索。感谢您的宝贵意见。
Forms.py
class MyUsersForm(ModelForm):
class Meta:
model = MyUsers
fields = ['created_by', ]
def __init__(self, user=None, **kwargs):
super(MyUsersForm, self).__init__(**kwargs)
if user is not None:
self.fields['created_by'].queryset = User.objects.filter(username=user)
的 Models.py
class MyUsers(models.Model):
user = models.OneToOneField(User, blank=True, null=True)
created_by = models.ForeignKey(User, related_name="created_by", blank=True, null=True)
答案 0 :(得分:0)
def create_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
my_user_form = MyUsersForm(request.POST)
if user_form.is_valid() and my_user_form.is_valid() and User.objects.filter(username=request.POST.get('user')).exists():
us = user_form.save()
my_us = my_user_form.save(commit=False)
my_us.user = us
my_us.save()
return HttpResponse('You have successfully created a user')
else:
return HttpResponse(' My_user_form is not validated')
else:
user_form = UserForm()
my_user_form = MyUsersForm(user=request.user)
return render(request, 'create_user.html', {'user_form': user_form, 'my_user_form': my_user_form})
答案 1 :(得分:0)
为什么my_user_form未经过验证和保存。我没有修改 init 中的查询集,而是使用语句
在视图中自行完成my_user_form.fields['created_by'] = forms.ModelChoiceField(User.objects.filter(username=request.user))
这解决了我的问题。但我仍然不知道它为什么不能在MyUsersForm的init方法中工作?