在URL中使用Django会话

时间:2014-06-19 03:24:16

标签: django session django-sessions

我目前正在使用Django让用户通过表单输入信息,然后将数据保存为会话。然后我使用此会话在其他视图中调用输入的数据。我想知道是否可以在我的网址中使用存储在这些会话中的输入数据?

def search(request):
    result = {}

    context = RequestContext(request) 

    t = request.session.get("tick")

    if request.method == 'POST':
        search = Search(data=request.POST)


        if search.is_valid():
            ticker = search.cleaned_data['search']

            request.session["tick"] = ticker

        else:
            print search.errors
    else:
        search = Search()

    return render_to_response('ui/search.html', {"result":result}, context) 

这是我对应的urls.py:

url(r'^search/$', views.search, name='search'),

我有什么方法可以在我的网址中使用保存为't = request.session.get(“tick”)'的会话,这样我就能得到与用户输入的数据相对应的网址?例如,如果用户输入'hello',那么我的网址将显示/ search / hello。

感谢。

1 个答案:

答案 0 :(得分:0)

是的,你可以这样做:

urls.py

url(r'^search/$', views.search, name='search'),
url(r'^search/(?P<query>.+)/$', views.search, name='search'),

views.py

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def search(request, query=None):
    result = {}
    context = RequestContext(request) 

    if request.method == 'POST':
        search = Search(data=request.POST)
        if search.is_valid():
            ticker = search.cleaned_data['search']
            return HttpResponseRedirect(reverse('search', kwargs={'query': ticker}))
        else:
            print search.errors
    else:
        search = Search()

    return render_to_response('ui/search.html', {"result":result}, context)