
django中的超链接,在template中可以用{% url 'app_name:url_name' param%}
(视频教程推荐:django视频教程)
其中app_name在工程urls中配置的namespace取值,url_name是在tweb/urls.py中配置的name对应,启用的param参数为可选项,当函数存在的时候带上参数对应的取值。
urls.py
1 2 3 4 | urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^tweb/',include('tweb.urls',namespace= 'tweb')),
]
|
tweb/urls.py
1 2 3 4 5 6 7 | 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
具体代码如下
1 2 3 4 5 6 7 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html>
< html >
< 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 %}" >{{ value.user }}</ a >
{{ value.email}}
< br >
{% endfor %}
</ body >
</ html >
|
user_page.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html>
< html >
< 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 >
|
相关教程推荐:python web教程