如何从views.py中的Django模板获取变量中的值?

2024-04-18 17:23:56 发布

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

我在django工作,希望在views.py中传递值 我的代码是

模板

     {% for doctor in doctor_list %}
       {% if citysearch == doctor.city %}
         <h1>Name of doctor is </h1>
          <form class="form" method="POST">
                  {% csrf_token %}
             <input type="submit", class="btn view", name="{{doctor.contactNumber}}" value="View Profile">
          </form>
        {% endif %}
        {% endfor %}

看法

    if request.method == 'POST':
        selectdocnum = request.POST.get["doctor.contactNumber"]
        print(selectdocnum)
        return redirect('patientPannel')

这不是返回doctor.contactNumber的值,错误是方法对象不可订阅


Tags: django代码pyform模板ifrequesth1
3条回答

这很正常,request.POST.get是一种方法。使用括号。正确的调用是:

selectdocnum = request.POST.get("doctorcontactnumber")

对于您的输入,您将namevalue混在一起。改为这样做:

<input type="hidden" name="doctorcontactnumber" value="{{doctor.contactNumber}}">

doctor.contactNumber是一个,而不是一个用于查找值或作为输入字段名称的键。为输入字段指定一个更好的名称,并改用该名称。您还使用了错误的输入类型,如果不希望编辑,请使用hidden,如果可以,请使用类似text的输入类型

<input type="hidden" name="contactNumber" value="{{doctor.contactNumber}}">

request.POST.get("contactNumber")

这是错误的

<input type="submit", class="btn view", name="{{doctor.contactNumber}}" value="View Profile">

我想你必须这么做

 {% for doctor in doctor_list %}
   {% if citysearch == doctor.city %}
     <h1>Name of doctor is </h1>
      <form class="form" method="POST">
              {% csrf_token %}
         <input type="text" value="{{doctor.contactNumber}}" name="doctorcontactnumber">
         <input type="submit" class="btn view" value="View Profile">
      </form>
    {% endif %}
    {% endfor %}

你的观点

    if request.method == 'POST':
    selectdocnum = request.POST.get["doctorcontactnumber"]
    print(selectdocnum)
    return redirect('patientPannel')

相关问题 更多 >