网络编程
位置:首页>> 网络编程>> Python编程>> 在django模板中实现超链接配置

在django模板中实现超链接配置

作者:lion_zhou  发布时间:2023-03-03 12:22:44 

标签:django,超链接,配置

django中的超链接,在template中可以用{% url 'app_name:url_name' param%}

其中app_name在工程urls中配置的namespace取值,url_name是在tweb/urls.py中配置的name对应 启用的param参数为可选项,当函数存在的时候带上参数对应的取值

urls.py


urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^tweb/',include('tweb.urls',namespace= 'tweb')),
]

tweb/urls.py


urlpatterns = [
 url(r'^index/',views.index),
 url(r'^addUser/',views.add_user),
 url(r'^show_index/',views.user),
 url(r'^user_page/(?P<ids>[0-9]+)$',views.user_page,name='user_page'), #ids匹配函数的参数 这样保证每个url都是可匹配到的
]

以上app_name对应的就是namespace url_name的取值,,tweb/urls.py中的name对应的是url_name

具体代码如下


def index(request):
 # user=models.user_info.objects.get(id=2) #通过id查找 也可以通过主键pk=1查找 结果一样
 user=models.user_info.objects.all()
 return render(request,'index.html',{'values':user})
def user_page(request,ids):
 user_info = models.user_info.objects.get(id=ids)
 return render(request,'user_page.html',{'user_info':user_info})

index.html


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<h1>hello,word</h1>
{% for value in values%}
<a href="{% url 'tweb1:user_page' value.id %}" rel="external nofollow" >{{ value.user }}</a>
{{ value.email}}
<br>
{% endfor %}
</body>
</html>

user_page.html


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>user page</title>
</head>
<body>
<h1>{{ user_info.user}}</h1>
<br>
<a>{{ user_info.email}}</a>
<br>
<a>{{ user_info.describe}}</a>
</body>
</html>

来源:https://blog.csdn.net/zhouxuan623/article/details/79383976

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com