模板中Django Formview的可见性

时间:2020-07-14 23:41:13

标签: django django-forms django-views

我已经按照此处的教程实施了基本的搜索功能:https://learndjango.com/tutorials/django-search-tutorial

我想通过在结果页面上显示搜索功能来扩展该教程,以允许重复搜索。但是,执行此操作时,无法将搜索表单显示在搜索结果页面上。显示搜索按钮,但未显示提供输入的字段。

相关代码:

home.html:

<div name="searchform">
    <form action="{% url 'search_results' %}" method="get">
        {{ form }}
        <input type="submit" value="Search">
    </form>
</div>
{% block content %}

{% endblock %}

search_results.html:

{% extends home.html}
{% block content %}
<h1>Search Results</h1>

<ul>
  {% for city in object_list %}
    <li>
      {{ city.name }}, {{ city.state }}
    </li>
  {% endfor %}
</ul>
{% endblock %}

Views.py:

from django.db.models import Q
from django.views.generic import TemplateView, ListView, FormView

from .models import City



class HomePageView(FormView):
    template_name = 'home.html'
    form_class = SearchForm

class SearchResultsView(ListView):
    model = City
    template_name = 'search_results.html'
    
    def get_queryset(self): 
        query = self.request.GET.get('q')
        object_list = City.objects.filter(
            Q(name__icontains=query) | Q(state__icontains=query)
        )
        return object_list

urls.py:


from django.urls import path

from .views import HomePageView, SearchResultsView

urlpatterns = [
    path('search/', SearchResultsView.as_view(), name='search_results'),
    path('', HomePageView.as_view(), name='home'),
]

forms.py:

from django import forms
class SearchForm(forms.Form):
    q = forms.CharField(label='', max_length=50, 
                    widget=forms.TextInput(attrs={'placeholder': 'Search Here'})             
                    )

任何有关如何解决此类问题的建议(或者如果我公然地做un-django-y),将不胜感激。

2 个答案:

答案 0 :(得分:1)

class HomePageView(FormView):
    template_name = 'home.html'
    form_class = SearchForm      # This line!

请记住也将form_class属性应用于SearchResultsView,否则将不解释任何形式。仅显示提交按钮,因为它不属于呈现的表单。

答案 1 :(得分:1)

您正在使用ListView,它是通用显示视图。 您需要使用get方法,然后才能通过表单再次进行搜索并停留在同一页面上。

class SearchResultsView(View):

    template_name = 'search_results.html'
    form_class = SearchForm

    def get(self, request):
        form = self.form_class()
        query = self.request.GET.get('q')
        context = {}
        context['form'] = form
        context['cities'] = City.objects.filter(
            Q(name__icontains=query) | Q(state__icontains=query)
        )
        return render(self.request, self.template_name, context)

使用 ListView 可以达到相同的结果,但是如果使用其他基于视图的类,效果会更好。

您可以检查文档。 here