是否可以在URL中获取传递给视图的变量。例如。我有一个包含许多位置的位置表。如果我单击某个位置,它将转到该位置的详细信息页面。位置ID将添加到URL。然后我有一个指向另一个页面/视图的链接,但想在下一个视图中引用位置ID。
urls.py:
url(r'^locations/get/(?P<location_id>\d+)/$', 'assessments.views.location'),
url(r'^locations/get/(?P<location_id>\d+)/next_page/$', 'assessments.views.next_page'),
view.py:
def location(request, location_id=1):
return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })
def next_page(request):
loc = Location.objects.get(id='id of that location')
答案 0 :(得分:1)
只需在视图功能中使用其名称
访问它def next_page(request,location_id):
loc = Location.objects.get(id=location_id)
答案 1 :(得分:1)
好的,我还不确定你究竟是什么意思,但我认为以下两个片段中的一个可以解决你的问题:
网址包含location_id,因此只需在next_page()
:
def location(request, location_id):
return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })
def next_page(request, location_id):
loc = Location.objects.get(id=location_id)
在request.session中传递location_id
:
def location(request, location_id):
request.session['selected_location'] = location_id
return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })
def next_page(request):
try:
selected_location = request.session['selected_location']
except KeyError:
# Not sure if 404 is the best status code here but you get the idea
raise Http404
loc = Location.objects.get(id=selected_location)