如何在Django中获取视图函数的URL路径 [英] How to get the url path of a view function in django

查看:456
本文介绍了如何在Django中获取视图函数的URL路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

view.py

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

urls.py

urlpatterns = patterns('',
    url( r'^view1$', 'app1.view.view1'),
)

我想获取<$的URL路径c $ c> view1 。我怎样才能做到这一点。
我想避免对任何URL路径进行硬编码,例如 xxx / view1。

I want to get the URL path of view1. How can I do this. I want to avoid hard coding any URL paths, such as "xxx/view1".

推荐答案

您需要< a href = https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls rel = noreferrer> 反向

from django.urls import reverse

reverse('app1.view.view1')

如果要查找URL并重定向到它,请使用 重定向

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

from django.urls import redirect 

redirect('app1.view.view1')

如果想更进一步,也不想对视图名称进行硬编码,则可以命名您的URL模式,并改用这些名称。

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

这篇关于如何在Django中获取视图函数的URL路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆