2017-01-20 56 views
0

我有一個簡單的搜索欄,我想保持數據的用戶submited並顯示在表單提交後的搜索欄。我怎樣才能做到這一點 ?提交後,如何在模板表單上保留GET實例?

我使用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.pyGig模型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的會話,但問題是,用戶只能看到他迴歸後的搜索內容索引頁面,任何建議?

回答

0

有一個簡單的方法來做到這一點:

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

表格後提交將保持文章的標題字段值和用它作爲輸入值。

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: [email protected] 
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') 
相關問題