Optional get parameters in django?

后端 未结 7 1645
后悔当初
后悔当初 2020-12-05 00:28

Can someone please explain how you can write a url pattern and view that allows optional parameters? I\'ve done this successfully, but I always break the url template tag.

7条回答
  •  爱一瞬间的悲伤
    2020-12-05 01:14

    Django urls are polymorphic:

    url(r'^so/(?P\d+)/$', 'myapp.so', name='sample_view'),
    url(r'^so/(?P\d+)/(?P.*)/$', 'myapp.so', name='sample_view'),
    

    its obious that you have to make your views like this:

    def sample_view(request, required, optional = None):
    

    so you can call it with the same name and it would work work url resolver fine. However be aware that you cant pass None as the required argument and expect that it will get you to the regexp without argument:

    Wrong:

    {% url sample_view required optional %}
    

    Correct:

    {% if optional %}
        {% url sample_view required optional %}
    {% else %}
        {% url sample_view required %}
    {% endif %}
    

    I dont know whether this is documented anywhere - I have discovered it by accident - I forgot to rewrite the url names and it was working anyway :)

提交回复
热议问题