How to get the url path of a view function in django

后端 未结 7 1301
醉话见心
醉话见心 2021-02-05 06:41

As an example:

view.py

def view1( request ):
    return HttpResponse( \"just a test...\" )

urls.py

urlpatterns = patter         


        
相关标签:
7条回答
  • 2021-02-05 07:07

    Yes, of course you can get the url path of view named 'view1' without hard-coding the url.

    All you need to do is - just import the 'reverse' function from Django urlresolvers.

    Just look at the below example code:

    from django.core.urlresolvers import reverse
    
    from django.http import HttpResponseRedirect
    
    def some_redirect_fun(request):
    
        return HttpResponseRedirect(reverse('view-name'))
    
    0 讨论(0)
  • 2021-02-05 07:12

    This depends whether you want to get it, if you want to get the url in a view(python code) you can use the reverse function(documentation):

    reverse('admin:app_list', kwargs={'app_label': 'auth'})
    

    And if want to use it in a template then you can use the url tag (documentation):

    {% url 'path.to.some_view' v1 v2 %}
    
    0 讨论(0)
  • 2021-02-05 07:15

    You can use the reverse function for this. You could specify namespaces and names for url-includes and urls respectively, to make refactoring easier.

    0 讨论(0)
  • 2021-02-05 07:17

    If you want the url of the view1 into the view1 the best is request.get_path()

    0 讨论(0)
  • 2021-02-05 07:20

    Universal approach

    1. install Django extensions and add it to INSTALLED_APPS

    2. Generate a text file with all URLs with corresponding view functions

    ./manage.py show_urls --format pretty-json --settings=<path-to-settings> > urls.txt

    like

    ./manage.py show_urls --format pretty-json --settings=settings2.testing > urls.txt

    1. Look for your URL in the output file urls.txt
        {
            "url": "/v3/blockdocuments/<pk>/",
            "module": "api.views.ganeditor.BlockDocumentViewSet",
            "name": "block-documents-detail",
        },
    
    0 讨论(0)
  • 2021-02-05 07:25

    You need reverse.

    from django.urls import reverse
    
    reverse('app1.view.view1')
    

    If you want to find out URL and redirect to it, use redirect

    from django.urls import redirect 
    
    redirect('app1.view.view1')
    

    If want to go further and not to hardcode your view names either, you can name your URL patterns and use these names instead.

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