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

2024-06-16 10:38:05 发布

您现在位置: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'}]>

Tags: 数据form模板requestservicebuttonselectclass
1条回答
网友
1楼 · 发布于 2024-06-16 10:38:05

您可以通过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

相关问题 更多 >