如何在不同页面上处理相同的表单(DRY)

时间:2018-01-14 12:37:50

标签: django python-3.x django-1.11

我有一个名为base.html的模板。它包含一个固定的搜索表单。我的所有其他模板都继承自base.html。我希望我的表单适用于每一页(现在我有10个不同的页面)。

一个愚蠢的解决方案是处理每个视图的表单,但它与DRY相反。

那么我怎样才能为所有观点处理一次表格?

注意:base.html只是一个模板,不会被视图直接使用。

1 个答案:

答案 0 :(得分:0)

您需要为“搜索”创建单独的应用,并且需要相应地创建视图和模板。

我的Django项目中有一个名为'Products'的应用程序,它有一个名为'Product'的模型,我使用搜索从该模型中搜索。

搜索/ views.py:

from django.shortcuts import render
from django.views.generic import ListView
from products.models import Product

class SearchProductView(ListView):
    template_name = "search/view.html"

    def get_context_data(self, *args, **kwargs):
        context = super(SearchProductView, self).get_context_data(*args, **kwargs)
        query = self.request.GET.get('q')
        context['query'] = query
        # SearchQuery.objects.create(query=query)
        return context

    def get_queryset(self, *args, **kwargs):
        request = self.request
        method_dict = request.GET
        query = method_dict.get('q', None) # method_dict['q']
        if query is not None:
            return Product.objects.search(query)
        return Product.objects.featured()
        '''
        __icontains = field contains this
        __iexact = fields is exactly this
        '''

search / templates / view.html(以呈现搜索结果):

{% extends "base.html" %}

{% block content %}
 <div class='row  mb-3'>
            {% if query %}
            <div class='col-12' >
                Results for <b>{{ query }}</b>
                <hr/>
            </div>
            {% else %}

            <div class='col-12 col-md-6 mx-auto py-5'>
               {% include 'search/snippets/search-form.html' %}

            </div>
            <div class='col-12'>
                <hr>
            </div>
            {% endif %}
</div>


        <div class='row'>



    {% for obj in object_list %}
        <div class='col'>

        {% include 'products/snippets/card.html' with instance=obj %}  

        {% if forloop.counter|divisibleby:3 %}
         </div> </div><div class='row'><div class='col-12'><hr/></div>
        {% elif forloop.counter|divisibleby:2 %}
            </div> </div><div class='row'><div class='col-12'><hr/></div>
        {% else %}
         </div>  
        {% endif %}


    {% endfor %}
</div>
{% endblock %}

搜索/模板/片段/搜索form.html:

<form method='GET' action='{% url "search:query" %}' class="form my-2 my-lg-0 search-form">
  <div class='input-group'>
    <input class="form-control" type="text" placeholder="Search" name='q' aria-label="Search" value='{{ request.GET.q }}'>
    <span class='input-group-btn'>
        <button class="btn btn-outline-success" type="submit">Search</button>
    </span>
    </div>
</form>

,最后是搜索应用的urls.py:

from django.conf.urls import url

from .views import (
        SearchProductView
        )

urlpatterns = [
    url(r'^$', SearchProductView.as_view(), name='query'),
]

并将其包含在主urls.py中:

url(r'^search/', include("search.urls", namespace='search')),

我希望这会有所帮助。

祝你好运!