what is reverse() in Django

前端 未结 7 1576
Happy的楠姐
Happy的楠姐 2020-11-30 16:40

When I read django code sometimes, I see in some templates reverse(). I am not quite sure what this is but it is used together with HttpResponseRedirect. How an

相关标签:
7条回答
  • 2020-11-30 17:18

    reverse() | Django documentation


    Let's suppose that in your urls.py you have defined this:

    url(r'^foo$', some_view, name='url_name'),
    

    In a template you can then refer to this url as:

    <!-- django <= 1.4 -->
    <a href="{% url url_name %}">link which calls some_view</a>
    
    <!-- django >= 1.5 or with {% load url from future %} in your template -->
    <a href="{% url 'url_name' %}">link which calls some_view</a>
    

    This will be rendered as:

    <a href="/foo/">link which calls some_view</a>
    

    Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

    You could just do:

    return HttpResponseRedirect('/foo/')
    

    But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

    Instead, you can say:

    from django.urls import reverse
    return HttpResponseRedirect(reverse('url_name'))
    

    This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

    This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

    0 讨论(0)
提交回复
热议问题