我正在使用一个表单将数据保存到其中。在
模型.py
class presciptiontemplates(models.Model):
templateid = models.AutoField(primary_key=True)
template = tinymce_models.HTMLField()
draft = models.BooleanField(default=False)
savedate = models.DateTimeField(default=datetime.now())
patientid = models.ForeignKey('Patient')
我从URL传递参数Patient Id。在
^{pr2}$如何将此参数保存到表单中
视图.py
def viewtemplate(request, patid):
userid = patid
form = templateform(request.POST)
if request.method == "POST":
if form.is_valid():
presciptiontemplates.patientid = userid
form.save()
return redirect('index')
else:
form = templateform()
return render(request, 'presapp/prescription.html', {'form': form})
在表单.py在
class templateform(forms.ModelForm):
class Meta:
model = presciptiontemplates
fields = ['template', 'draft']
widgets = {
'template': TinyMCE(),
'draft': forms.CheckboxInput()
}
labels = {
"patientid": _("Patient ID"),
}
def __init__(self, *args, **kwargs):
super(ThatForm, self).__init__(*args, **kwargs)
self.fields['template'].required = True
这给了我一个错误
[Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'patientid'
Django 1.10.4
Python 3.5.2
Windows 7
问题在于:
在您的模型中,patientid是Patient模型的外键,因此它需要一个Patient model对象,而不是patid。 因此,首先获取Patient对象,然后将其分配给patientid,如下所示:
^{pr2}$假设
templateform
是一个模型形式。在您可以在save方法中使用
commit=False
参数,然后使用所需参数再次保存对象。在根据代码更改的简短片段
要将userid值添加到新对象中,可以使用ModelForm。在
只需使templateform继承自ModelForm而不是Form类。在
现在,您可以执行以下操作:
^{pr2}$相关问题 更多 >
编程相关推荐