我在Django中的index.html模板具有以下内容:
<ul>
<li><a href="{% url 'quantities' %} value="1">All</a></li>
<li><a href="{% url 'quantities' %} value="2">Subset1</a></li>
<li><a href="{% url 'quantities' %} value="3">Subset2</a></li>
<li><a href="{% url 'quantities' %} value="4">Subset3</a></li>
</ul>
因此链接到相同的模板,但(取决于点击的链接)我想写我的app / views.py中的函数:
def quantities(request):
if value == "1":
levels = Model_1.objects.all()
elif value == "2":
levels = Model_1.objects.filter(createria=2)
elif value == "3":
levels = Model_1.objects.filter(createria=3)
elif value == "4":
levels = Model_1.objects.filter(createria=4)
我可以获取上一页中点击链接的值吗?
答案 0 :(得分:6)
我最好传递url中的值而不是url参数:
<ul>
<li><a href="{% url 'quantities_all' %}>All</a></li>
<li><a href="{% url 'quantities' '2' %}>Subset1</a></li>
<li><a href="{% url 'quantities' '3' %}>Subset2</a></li>
<li><a href="{% url 'quantities' '4' %}>Subset3</a></li>
</ul>
您的观点将如下所示:
def quantities(request, value=None):
if value in ('2', '3', '4'):
levels = Model_1.objects.filter(createria=int(value))
else:
levels = Model_1.objects.all()
...
不要忘记改变你的网址:
url(r'^quantities/$', 'app.views.quantities', name='quantities_all'),
url(r'^quantities/(\d+)/$', 'app.views.quantities', name='quantities'),
答案 1 :(得分:1)
将值作为GET参数传递:
<ul>
<li><a href="{% url 'quantities' %}?value=1">All</a></li>
<li><a href="{% url 'quantities' %}?value=2">Subset1</a></li>
<li><a href="{% url 'quantities' %}?value=3">Subset2</a></li>
<li><a href="{% url 'quantities' %}?value=4">Subset3</a></li>
</ul>
获取视野:
def quantities(request):
value = request.GET.get('value', '1')
if value == "1":
levels = Model_1.objects.all()
elif value == "2":
levels = Model_1.objects.filter(createria=2)
elif value == "3":
levels = Model_1.objects.filter(createria=3)
elif value == "4":
levels = Model_1.objects.filter(createria=4)
答案 2 :(得分:1)
您需要在网址配置中捕获数量。 https://docs.djangoproject.com/en/1.7/topics/http/urls/
这比传递GET参数更好,因为你有一个链接,像http://example.org/quantities/4/
这样的链接看起来更好,而在Django这是一个惯例:
<ul>
<li><a href="{% url 'quantities' 1 %}">All</a></li>
<li><a href="{% url 'quantities' 2 %}">Subset1</a></li>
<li><a href="{% url 'quantities' 3 %}">Subset2</a></li>
<li><a href="{% url 'quantities' 4 %}">Subset3</a></li>
</ul>
所以你的urls.py看起来像:
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^quantities/(\d+)/$', views.quantities), )
views.py来自另一个答案
def quantities(request, value):
if value in ('2', '3', '4'):
levels = Model_1.objects.filter(createria=int(value))
else:
levels = Model_1.objects.all()
...