将数据从视图传递到模板django python?

时间:2018-05-03 21:15:45

标签: python django

我正在尝试将数据从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'}]>

1 个答案:

答案 0 :(得分:0)

您可以通过get_context_data() more info here

发送变量
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