【问题标题】:How to pass values to input field's value with spaces如何使用空格将值传递给输入字段的值
【发布时间】:2021-09-03 16:01:57
【问题描述】:
<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 ”。

【问题讨论】:

  • 在你的 javascript 或数据库中使用 Trim 函数你可以使用 LTRIM、RTRIM 但在 db 级别进行修剪不是一个好主意。

标签: django django-models django-rest-framework django-views django-forms


【解决方案1】:

.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={{ first_name }} 而不是value={{ doctorName.name }},但请确保您拥有id="doctorName.id",如果需要,您可以在其他地方参考此信息。

【讨论】:

  • 如果此解决方案解决了您的问题,也许您可​​以接受它作为您的答案。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多