我已经尝试使用ModelForm保存外键,但是我收到了这个错误:
The LabRequestForm could not be created because the data didn't validate.
这是我的代码:
model.py
class LabRequestForm(models.Model):
# lab request form
product_name = models.ForeignKey(ProductName, on_delete=models.CASCADE)
ref_no = models.CharField(max_length=200, unique=True)
date = models.DateTimeField()
batch_number = models.CharField(max_length=200, unique=True)
sampling_time = models.DateTimeField()
lab_test_number = models.CharField(null=True, max_length=200)
forms.py
class LabRequestModelForm(ModelForm):
class Meta:
model = LabRequestForm
fields = '__all__'
views.py
@login_required
def sampler(request):
detect_user = Account.objects.get(id=request.user.id)
if detect_user.is_sampler:
if request.method == "POST":
prod_name = ProductName.objects.get(product_name=request.POST.get('product_name'))
lab_req_form = LabRequestModelForm(request.POST)
lab_req_form_obj = lab_req_form.save(commit=False)
lab_req_form_obj.product_name = prod_name
if lab_req_form_obj.is_valid():
lab_req_form_obj.save()
messages.info(request, 'Form Saved')
else:
print('not valid')
messages.error(request, "Form is not valid")
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
手动我检查了每个POST数据,它们是正确的。所以我怀疑lab_req_form.save(commit=False)
是罪魁祸首。
答案 0 :(得分:0)
在验证发生之前,您正在调用save。您的save(commit=False)
应位于if lab_req_form.is_valid()
下。你也在对象上调用is_valid
,而不是在表单上。这应该工作
@login_required
def sampler(request):
detect_user = Account.objects.get(id=request.user.id)
if detect_user.is_sampler:
if request.method == "POST":
prod_name = ProductName.objects.get(product_name=request.POST.get('product_name'))
lab_req_form = LabRequestModelForm(request.POST)
# should validate lab_req_form not lab_req_form_obj
if lab_req_form.is_valid():
# moved here
lab_req_form_obj = lab_req_form.save(commit=False)
lab_req_form_obj.product_name = prod_name
lab_req_form_obj.save()
messages.info(request, 'Form Saved')
else:
print('not valid')
messages.error(request, "Form is not valid")
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))