假设有一个带有 PHP 样式参数的 URL,例如:
http://example.com/blah?param1=val1¶m2=val2
我想把它们的值放入模板生成的HTML中,
我该如何实现?
假设有一个带有 PHP 样式参数的 URL,例如:
http://example.com/blah?param1=val1¶m2=val2
我想把它们的值放入模板生成的HTML中,
我该如何实现?
{{ request.resolver_match.kwargs.argument }}
作为传递给视图的函数参数:
def myview(request, argument):
在Django 1.9上进行测试。
我们可以在Django模板中这样获取URL参数 -http://djangopmt.localhost/tasks/?project=1&status=3&priority=High&search=StudyGyaan.com
{{request.GET.project}}
{{request.GET.status}}
{{request.GET.priority}}
{{request.GET.search}}
如果您想在 Django 视图中获取 URL 参数,可以按以下方式获取:
request.GET.get('project', None)
request.GET.get('status', None)
request.GET.get('priority', None)
request.GET.get('search', None)
https://example.com/?fruits=apple&meat=beef
views.py
中按照下面的示例获取参数。*我的答案更详细地解释了这一点。# "views.py"
from django.shortcuts import render
def index(request):
print(request.GET['fruits']) # apple
print(request.GET.get('meat')) # beef
print(request.GET.get('fish')) # None
print(request.GET.get('fish', "Doesn't exist")) # Doesn't exist
print(request.GET.getlist('fruits')) # ['apple']
print(request.GET.getlist('fish')) # []
print(request.GET.getlist('fish', "Doesn't exist")) # Doesn't exist
print(request.GET._getlist('meat')) # ['beef']
print(request.GET._getlist('fish')) # []
print(request.GET._getlist('fish', "Doesn't exist")) # Doesn't exist
print(list(request.GET.keys())) # ['fruits', 'meat']
print(list(request.GET.values())) # ['apple', 'beef']
print(list(request.GET.items())) # [('fruits', 'apple'), ('meat', 'beef')]
print(list(request.GET.lists())) # [('fruits', ['apple']), ('meat', ['beef'])]
print(request.GET.dict()) # {'fruits': 'apple', 'meat': 'beef'}
print(dict(request.GET)) # {'fruits': ['apple'], 'meat': ['beef']}
print(request.META['QUERY_STRING']) # fruits=apple&meat=beef
print(request.META.get('QUERY_STRING')) # fruits=apple&meat=beef
return render(request, 'index.html')