Django:表单实例未加载

时间:2017-05-02 11:42:04

标签: python django django-forms

我正在使用视图将对象加载到表单上。我正在使用Material Form Library

我已经通过Jquery在表单上添加了 CKEditor ,表单已保存,但我似乎无法将数据加载到表单上。

urls.py

url(r'^viewprescription/(?P<tid>\d+)/$', views.get_template, name='viewtemplates'),

views.py

def get_template(request, tid):
    template = presciptiontemplates.objects.get(templateid=tid)
    if request.method == "GET":
        form = templateform(request.GET, instance=template)
        messages.success(request, 'Prescription loaded')
        print(form)
        if form.is_valid():
            form.save(commit=False)
            Presciptiontemplates = presciptiontemplates()
            Presciptiontemplates.savedate = datetime.now()
            Presciptiontemplates.template = form.cleaned_data.get('template')
            Presciptiontemplates.draft = form.cleaned_data.get('draft')
            Presciptiontemplates.save()
            messages.success(request, 'Prescription Saved Successfully')
    else:
        form = templateform(request.GET, instance=template)
        messages.error(request, 'Please Try Again')
        print(form)
    return render(request, 'presapp/viewtemplate.html', {'form': form})

forms.py

class templateform(forms.ModelForm):
    template = forms.CharField(widget=forms.Textarea, label='')
    draft = forms.BooleanField(required=False)
    layout = Layout(Fieldset('Template'), ('template'), ('draft'))

    class Meta:
        model = presciptiontemplates
        fields = ['template', 'draft']

models.py

class presciptiontemplates(models.Model):
    templateid = models.AutoField(primary_key=True)
    template = RichTextField()
    draft = models.BooleanField(default=False)
    savedate = models.DateTimeField(default=datetime.now())
    patientid=models.IntegerField()

viewtemplate.html

<div id="preview-content">
  <form method="POST" style="margin-top:20px;">
    {% csrf_token %}
     {% form %} 
    {% endform %}
    <div class="" style="margin-top:20px ;">
      <button class="btn waves-effect waves-light left" type="submit">Submit
    <i class="material-icons right">add_circle</i>
    </button>
  </form>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您需要从视图上下文传递表单模板标签,即:

{% form form=form %}{% endform %}

这就是它在文档快速入门中所说的内容:http://forms.viewflow.io/