如何在提交后将GET实例保留在模板表单上?

时间:2017-01-20 01:25:20

标签: python django django-views

我有一个简单的搜索栏,我想保留用户提交的数据,并在表单提交后在搜索栏上显示。我怎么能这样做?

我正在使用GET搜索方法,但我没有在任何模型上保存任何搜索的项目,我不愿意,我想知道是否有其他方法可以在不使用数据库存储的情况下显示它

以下是我的代码:

views.py

def index(request):
    allGigs = Gig.objects.filter(status=True)
    context = {'gigs': allGigs}
    return render(request, 'index.html', context)

def search_gigs(request):
    title = request.GET['title']
    request.session['title'] = title #a try with session, but the data is kept once the user returns to front page...
    gigs = Gig.objects.filter(title__contains=title)
    return render(request, 'index.html', {"gigs": gigs})

models.py Gig模型有title CharField。

的index.html

<form role="search" method="GET" action="{% url 'search' %}">
    <input type="text" name="title">
    <input type="submit" value="submit">
</form>

urls.py

url(r'^search/$', views.search_gigs, name='search'), #example : /search/?title=my_search_word
url(r'^$', views.index, name='index'),

我考虑过使用Django Sessions,但问题是用户只能在返回索引页面后看到他搜索的内容,有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您可以在视图中使用此粘滞查询方法装饰器。

from urllib.parse import urlencode
try:
    import urlparse
except ImportError:
    from urllib import parse as urlparse

import wrapt

from django.http import HttpResponseRedirect


'''
Originally From:
https://www.snip2code.com/Snippet/430476/-refactor--Django--sticky-URL-query-para
'''

"""
File: decorators.py
Author: timfeirg
Email: kkcocogogo@gmail.com
Github: https://github.com/timfeirg/
Description: remember_last_query_params is from
http://chase-seibert.github.io/blog/2011/09/02/django-sticky-url-query-parameters-per-view.html
"""


class sticky_query(object):

    """Stores the specified list of query params from the last time this user
    looked at this URL (by url_name). Stores the last values in the session.
    If the view is subsequently rendered w/o specifying ANY of the query
    params, it will redirect to the same URL with the last query params added
    to the URL.

    url_name is a unique identifier key for this view or view type if you want
    to group multiple views together in terms of shared history

    Example:

    @remember_last_query_params("jobs", ["category", "location"])
    def myview(request):
        pass

    """

    def __init__(self, views_name, query_params):
        self._cookie_prefix = views_name + '_'
        self._query_params = list(set(
            query_params + ['page', 'paginate_by', 'order_by_fields']))

    def _get_sticky_params(self, request):
        """
        Are any of the query parameters we are interested in on this request
        URL?
        """
        gum = []
        for current_param, v in request.GET.items():
            if current_param in self._query_params:
                gum.append(current_param)
        return gum

    def _get_last_used_params(self, session):
        """
        Gets a dictionary of JUST the params from the last render with values
        """
        litter = {}
        for k in self._query_params:
            last_value = session.get(self._cookie_prefix + k, None)
            if last_value:
                litter[k] = last_value

        return litter

    def _digest(self, current_url, litter):
        """
        update an existing URL with or without paramters to include new
        parameters from
        http://stackoverflow.com/questions/2506379/add-params-to-given-url-in-python
        """
        parse_res = urlparse.urlparse(current_url)
        # part 4 == params
        query = dict(urlparse.parse_qsl(parse_res[4]))
        query.update(litter)
        query = urlencode(query)
        parse_res = urlparse.ParseResult(
            parse_res[0], parse_res[1], parse_res[2], parse_res[3], query,
            parse_res[5])
        new_url = urlparse.urlunparse(parse_res)
        return new_url

    @wrapt.decorator
    def __call__(self, wrapped, instance, args, kwargs):
        request = args[0]
        session = request.session
        query = request.GET
        gum = self._get_sticky_params(request)
        if gum:
            for k in gum:
                sticky_key = self._cookie_prefix + k
                session[sticky_key] = query[k]
        else:
            meta = request.META
            litter = self._get_last_used_params(session)
            if litter:
                current_url = '{0}?{1}'.format(
                    meta['PATH_INFO'], meta['QUERY_STRING'])
                new_url = self._digest(current_url, litter)
                return HttpResponseRedirect(new_url)

        return wrapped(*args, **kwargs)

在您的视图中使用此装饰器:

from django.utils.decorators import method_decorator

@method_decorator(sticky_query("search_page", ["title"]), name='dispatch')

答案 1 :(得分:0)

有一种简单的方法:

<input type="text" name="title" value="{{ request.POST.title }}">

表单提交后,它将保留POST标题字段值并将其用作输入值。