首页 > 解决方案 > 如何使用空格将值传递给输入字段的值

问题描述

<form action="handleAppointment/" method="post" >
        {% csrf_token %}
        <div class="inputfield">
            <label for="doctor" class="label">Doctor</label>
            <input type="text" name="doctor" id="doctor" class="input" value={{ doctorName.name }} >
        </div>

这是我的表格,我想从数据库中获取完整值。但这里 {{doctorName.name}} 显示的是空格之前的值。

def bookAppointment(request , id ):
  doctor = Doctor.objects.filter(id = id ).first()
  print(doctor.name)

  context = {'doctorName': doctor}
  return render(request , 'patient/appointmentForm.html' , context)

运行此代码后,它在终端中显示“Tapan Shah”作为输出。这是全名,但它在前端的空格值之前显示“ Tapan ”。

标签: djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-forms

解决方案


文件内.py...

bookAppointment函数中,您可以将额外的变量传递给模板。例如:

def bookAppointment(request, id ):
  doctor = Doctor.objects.filter(id=id).first()
  first_name = doctor.name.split()[0]  # see here...

  context = {'doctorName': doctor, 'first_name': first_name}
  return render(request, 'patient/appointmentForm.html', context)

请注意,doctor.name.split()然后将根据医生的姓名制作一个列表,例如 ['firstname', 'lastname']。通过使用doctor.name.split()[0]将调用医生的名字并将其分配给变量 first_name。

在 .html 文件中...

<div class="inputfield">
    <label for="doctor" class="label">Doctor</label>
    <input type="text" name="doctorName.name" id="doctorName.id" class="input" value={{ first_name }} >
</div>

因此,不要让value={{ doctorName.name }}您只使用value={{ first_name }},但请确保您拥有id="doctorName.id"可以在需要时在其他地方引用此信息的信息。


推荐阅读