{%if}用于在Django HTML文件中隐藏表格视图

时间:2018-08-07 17:05:06

标签: django jinja2

我在用html文件中的{if}创建正确的公式时遇到了一个小问题。我想查看所有表的视图,如果用户不进行任何搜索,该表将不可用。 但是在我的情况下,它始终可用,我无法隐藏它。我将不胜感激。

我的html文件

{% extends 'base.html' %}
{% load widget_tweaks %}

{% block title %}
    <hr class="featurette-divider">
<h1><center>Wyszukiwarka firm</center></h1>
    <hr class="featurette-divider">
{% endblock %}

{% block content %}
  <form method="get">
    <div class="well">
      <h4 style="margin-top: 1"><center>Wpisz nazwę firmy</center></h4>
      <div class="row " >
        <div class="form-group form-group-lg  " >
          <div class="col-sm-12 " >
          {{ filter.form.label_tag }}
          {% render_field filter.form.name class="form-control" %}
          </div>
        </div>
        <div class="form-group col-sm-8 col-md-6">
          {{ filter.form.groups.label_tag }}
        </div>
      </div>
      <button type="submit" class="btn btn-primary btn-block">
        <span class="glyphicon glyphicon-search"></span> Search
      </button>
    </div>
  </form>

  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Nazwa</th>
        <th>Rating</th>
        <th>Ilość opinii</th>
        <th>Dodatkowe informacje</th>
        <th>Miasto</th>
      </tr>
    </thead>
    <tbody>
      {% for wine in filter.qs %}
        <tr>
          <td><h4><a href="{% url 'reviews:wine_detail' wine.id %}">
          {{ wine.name }}
          </a></h4></td>
          <td>{{ wine.average_rating | floatformat }} average rating</td>
          <td>{{ wine.review_set.count }} reviews</td>
          <td>{{ user.date_joined }}</td>
          <td>
            {% for group in user.groups.all %}
              {{ group }}
            {% empty %}
              <em class="text-muted">Brak inf. o miescie</em>
            {% endfor %}
          </td>
        </tr>
      {% empty %}
        <tr>
          <td colspan="5">No data</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>


{% endblock %}

我的views.py

def review_list(request):
    latest_review_list = Review.objects.order_by('-pub_date')[:9]
    context = {'latest_review_list':latest_review_list}
    return render(request, 'reviews/review_list.html', context)


def review_detail(request, review_id):
    review = get_object_or_404(Review, pk=review_id)
    return render(request, 'reviews/review_detail.html', {'review': review})


def wine_list(request):
    wine_list = Wine.objects.order_by('-name')
    context = {'wine_list':wine_list}
    return render(request, 'reviews/wine_list.html', context)


def wine_detail(request, wine_id):
    wine = get_object_or_404(Wine, pk=wine_id)
    form = ReviewForm()
    return render(request, 'reviews/wine_detail.html', {'wine': wine, 'form': form})

@login_required
def add_review(request, wine_id):
    wine = get_object_or_404(Wine, pk=wine_id)
    form = ReviewForm(request.POST)
    if form.is_valid():
        rating = form.cleaned_data['rating']
        comment = form.cleaned_data['comment']
        user_name = request.user.username
        review = Review()
        review.wine = wine
        review.user_name = user_name
        review.rating = rating
        review.comment = comment
        review.pub_date = datetime.datetime.now()
        review.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('reviews:wine_detail', args=(wine.id,)))

    return render(request, 'reviews/wine_detail.html', {'wine': wine, 'form': form})

def user_review_list(request, username=None):
    if not username:
        username = request.user.username
    latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
    context = {'latest_review_list':latest_review_list, 'username':username}
    return render(request, 'reviews/user_review_list.html', context)

def search(request):
    review_list = Review.objects.all()
    review_filter = ReviewFilter(request.GET, queryset=review_list)
    return render(request, 'reviews/my_search.html', {'filter': review_filter})

def search_wine(request):
    wine_list = Wine.objects.all()
    wine_filter = WineFilter(request.GET, queryset=wine_list)
    return render(request, 'reviews/my_search_1.html', {'filter': wine_filter})

我的filtrs.py

from django.db import models
from .models import Review, Wine
import django_filters

class ReviewFilter(django_filters.FilterSet):
    comment = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Review
        fields = ['comment', 'wine', 'rating', 'user_name']

class WineFilter(django_filters.FilterSet):
    class Meta:
        model = Wine
        fields = ['name',]

编辑 我认为,解决问题的好办法可能是这样的( 在一个简化的示例中):

{% if a != c %}
{% for wine in filter.qs %}
    <li>{{ wine.name }} - {{ wine.get_full_name }}</li>
{% endfor %}
{% else %}
<p>Search for something</p>
{% endif %}

其中a =数据库中所有索引的“名称” 并且b =表中的所有行(但是如何计算)?

1 个答案:

答案 0 :(得分:1)

已编辑,我认为您的问题编辑可以解决您所面临的问题。您基本上希望网页显示

  

“搜索内容”

如果在呈现的表单下方没有任何搜索,并且当用户搜索时,您想显示所有拟合的值,对吗?

然后,您的视图必须处理该逻辑,并且不得在模板中执行检查(如您在编辑中建议的!= c然后呈现过滤器),因为这会导致两个模块,这是不希望的。在这种情况下,按照我的方式进行的操作是我建议的略微修改,即,在您的视图中使用基于request.method的支票,以及使用POST作为表单的方法。您可以在Django Coupling中阅读有关request.method的信息。

解决问题的方法:

  1. 将表单方法更改为post,并将CSRF令牌添加到表单中以处理POST请求。
<form method="post">
{% csrf_token %}
...

  1. 在搜索视图中添加以下逻辑:
    
    def search_view(request):
        wine_list = Wine.objects.all()
        wine_filter = WineFilter(request.POST, queryset=wine_list)
        if request.method == "POST":
            return render(request, 'reviews/search.html', context={'filter': wine_filter, 'searched': True})
        else:   # Handle GET request
            return render(request, 'reviews/search.html', context={'filter': wine_filter})

3。您的模板如上所述进行更改:

{% if searched %}
{% for wine in filter.qs %}
    <li>{{ wine.name }} - {{ wine.get_full_name }}</li>
{% endfor %}
{% else %}
    <p>Search for something</p>
{% endif %}

将FORM方法更改为POST的原因是因为发出GET请求时,页面的状态未更改。但是,您要根据是否进行搜索来更新页面的状态。这需要POST请求。我已将您重定向到HTTP方法的出色答案:here

工作屏幕截图:

When do you use POST and when do you use GET?
Initial Page