首页 > 解决方案 > 将数据从视图传递到模板django python?

问题描述

我正在尝试将数据从 django 视图传递到我的模板,但是由于某种原因,当我尝试在模板中呈现数据时,什么也没有发生。然而我可以看到我从模型中得到了正确的数据。我可能做错了什么?

views.py

    class PatientBill(CreateView):
        model = PatientBill
        form_class = PatientBillform



        def get(self,request):
            form=PatientBillform();
            billingservice = Billing.objects.values()
            print ('Billingservice',billingservice)

            return render(request,'cashier/patientbill.html',{'form':form,'Billingservice':billingservice})

patientbill.html
<form method="post">
    {% csrf_token %}
    {{ form.patientid }}
      <br>

      {{ form.totalbill }}
    <br>


   <label  style="font-weight: bold;">Choose a service </label>  <select  id ="service" style="width: 50%;height: 30px;margin-left: 75px" >



<option disabled selected> -- select an option -- </option>
      {% for bservice in Billingservice %}
      <option name = "servicedata" value={{bservice.service}}</option>
      {% endfor %}


                                </select>


    <button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored subtn">Calculate</button>
  </form>

Billingservice - Billingservice <QuerySet [{'id': 2, 'created': datetime.datetime(2018, 5, 3, 13, 28, 58, 170762, tzinfo=<UTC>), 'price': '2000', 'service': 'Consultation'}]>

标签: pythondjango

解决方案


您可以通过此处的更多信息发送变量get_context_data()

class PatientBill(CreateView):
    model = PatientBill
    form_class = PatientBillform 

    def get_context_data(self, **kwargs):
        ctx = super(PatientBill, self).get_context_data(**kwargs)
        form=PatientBillform()
        billingservice = Billing.objects.values()

        ctx['form'] = form
        ctx['Billingservice'] = billingservice
        return ctx

推荐阅读