django url 在模板中添加参数的正确方法
django url in template correct way to add parameter
在views.py
class LaViewSet(viewsets.ModelViewSet):
serializer_class = IlSerializer
def get_queryset(self):
ilfiltro = self.kwargs['miopar']
return models.Pippo.objects.filter(pippo=ilfiltro)
在url.py
url(r'^pippo/(?P<miopar>.+)', views.LaViewSet.as_view({'get': 'list'}), name="Serializzata"),
这是一个有效的 url:
http://127.0.0.1:8000/pippo/1
但如果我输入模板:
{% url '1' 'Serializzata' %};
或
{% url 'Serializzata'?1 %};
不断收到此错误:
TemplateSyntaxError: Could not parse the remainder: '?1' from
''Serializzata'?1'
试试这个:
<a href="{% url 'Serializzata' 1 %}">
来自docs:
url
Returns an absolute path reference (a URL without the domain name)
matching a given view and optional parameters. Any special characters
in the resulting path will be encoded using iri_to_uri().
This is a way to output links without violating the DRY principle by
having to hard-code URLs in your templates:
{% url 'some-url-name' v1 v2 %}
所以在你的情况下:
{% url 'Serializzata' 1 %}
在views.py
class LaViewSet(viewsets.ModelViewSet):
serializer_class = IlSerializer
def get_queryset(self):
ilfiltro = self.kwargs['miopar']
return models.Pippo.objects.filter(pippo=ilfiltro)
在url.py
url(r'^pippo/(?P<miopar>.+)', views.LaViewSet.as_view({'get': 'list'}), name="Serializzata"),
这是一个有效的 url:
http://127.0.0.1:8000/pippo/1
但如果我输入模板:
{% url '1' 'Serializzata' %};
或
{% url 'Serializzata'?1 %};
不断收到此错误:
TemplateSyntaxError: Could not parse the remainder: '?1' from ''Serializzata'?1'
试试这个:
<a href="{% url 'Serializzata' 1 %}">
来自docs:
url
Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri().
This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:
{% url 'some-url-name' v1 v2 %}
所以在你的情况下:
{% url 'Serializzata' 1 %}