在我的Django HTML模板中,由于城市中城市的%循环,我的文本重复

时间 2019-02-20
阅读 35
点赞 0
收藏 0
连接almaz

由于%for%循环,HTML中的文本重复。我已经尝试过将%移动到%之外的%为。然后我就消失了。

这是我的HTML模板

{% for city in cities %}
  {% if city.author.access_challenge %}
    <p class="small text-center"> In order to get information about this  contact us through almaz@protonmail.com </p>
  {% else %}
    <table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
     <tbody>
      <tr>
       <td><a class="text-uppercase" href="{% url 'users:address' city.pk %}">{{ city.city }}</a></td>
      </tr>
     </tbody>
    </table>
{% endif %}
{% endfor %}

这是我的观点。

def cities(request, pk):

    country = Post.objects.get(id=pk).country
    cities = Post.objects.filter(country=country).distinct('city')

    context = {
        'cities':cities,
        'country':country
    }

    return render(request, 'users/cities.html', context)

我也试着改变我的观点。

def cities(request, pk):

    country = Post.objects.get(id=pk).country
    ci = Post.objects.filter(country=country).distinct('city')
    cit = list(ci)
    for city in cit:
        for cities in cit:
            context = {
                'cities':cities,
                'country':country
            }

    return render(request, 'users/cities.html', context)

但是当我使用for循环时,我得到一个错误,即post是不可迭代的。

建议答案

我是这样解决的:

我的视图.py现在:

def cities(request, pk):

    country = Post.objects.get(id=pk).country
    cities = Post.objects.filter(country=country).distinct('city')
    author = Post.objects.get(id=pk).author

    context = {
        'cities':cities,
        'country':country,
        'author':author,

    }

    return render(request, 'users/cities.html', context)

我的views.py以前是:

def cities(request, pk):

    country = Post.objects.get(id=pk).country
    cities = Post.objects.filter(country=country).distinct('city')

    context = {
        'cities':cities,
        'country':country
    }

    return render(request, 'users/cities.html', context)

以前我的HTML也有错误。但现在,它的工作没有任何错误:

  {% if author.access_challenge %}

    <p class="text-center col-sm-12"> In order to get info about this country contact <strong>emeupci@protonmail.com</strong></p>

    {% else %}

    {% for city in cities %}
    <table class="table table-hover text-left col-sm-12" style="table-layout: fixed; word-wrap: break-word;">
       <tbody>
        <tr>
         <td><a class="text-uppercase" href="{% url 'users:address' city.pk %}">{{ city.city }}</a></td>
        </tr>
       </tbody>
      </table>
    {% endfor %}

    {% endif %}

👍 0