Django:将URL请求参数保存到表单中

2024-10-02 20:41:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个表单将数据保存到其中。在

模型.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 

Tags: pyselfformtruedefault表单modelsrequest
3条回答

问题在于:

presciptiontemplates.patientid = userid

在您的模型中,patientidPatient模型的外键,因此它需要一个Patient model对象,而不是patid。 因此,首先获取Patient对象,然后将其分配给patientid,如下所示:

^{pr2}$

假设templateform是一个模型形式。在

您可以在save方法中使用commit=False参数,然后使用所需参数再次保存对象。在

根据代码更改的简短片段

...
if request.method == "POST":
    if form.is_valid():
        obj = form.save(commit=False)
        obj.patientid = userid
        obj.save()
    return redirect('index')
else:
...

要将userid值添加到新对象中,可以使用ModelForm。在

只需使templateform继承自ModelForm而不是Form类。在

class templateform(forms.ModelForm):
    class Meta:
        model = presciptiontemplates

现在,您可以执行以下操作:

^{pr2}$

相关问题 更多 >