【问题标题】:Unsure why object being passed through as string不确定为什么对象作为字符串传递
【发布时间】:2021-01-16 18:38:53
【问题描述】:

我有一个使用数据库中城市列表的自动完成下拉列表。我正在使用 django 城市。我希望能够将其显示为 (city.name , city.country.name) 在我的 HTML 中。但它说城市是一个字符串。有人可以向我解释为什么在我的 destination_form.html 中 {{ city }} 是一个字符串而不是一个城市对象

views.py

def add_destination(request,trip_id):
    city_list = City.objects.all()
    dict = {
        'city_list':city_list,
        'trip_id':trip_id,
    }
    if request.method=="POST":
        print("Resquest: ")
        print(request.POST)
        city = request.POST['city']
        print(city.country)

    return render(request,'trips/destination_form.html',dict)

destination_form.html

{% extends "trips/trip_base.html" %}
{% load bootstrap3 %}
{% block trip_content %}
<h4>Add Destination!</h4>
<form method="POST" id='destinanationForm' action="{% url 'trips:add_destination' trip_id=trip_id%}">
  {% csrf_token %}
  <label for="city">City: </label>
  <input id="city" list="city_list" placeholder="Search City..." class="form-control" style="width:300px" name="city">
  <datalist id="city_list">
    {% for city in city_list %}
    <option value="{{ city }}" >{{city.name}} , {{ city.country.name }}</option>
    {% endfor %}
  </datalist>
  <label for="start_date">Start Date: </label>
  <input id="start_date" type="date" name="start_date" value="{{ start_date }}">
  <label for="end_date">End Date: </label>
  <input id="end_date" type="date" name="end_date" value="{{ end_date }}">
<input type="submit" class="btn btn-primary btn-large" value="Create">
</form>
{% endblock %}

urls.py

path('single_trip/<str:trip_id>/add_destination',views.add_destination,name='add_destination'),

【问题讨论】:

    标签: python html django django-views django-templates


    【解决方案1】:

    因为对象在 City 模型中使用 str 表示。因此,每当您使用 print 或 str 访问该对象时,您的模板都会返回该名称:

    def __str__(self):
        return force_text(self.name)
    

    您应该使用 {{ city.pk }} 而不是 {{ city }} 或模板中可用的任何唯一字段。

    有关字符串表示的更多信息,请参阅Python str() and repr() functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多