django网页开发:2. 模板、url、超链接

PEP 8: expected 2 blank lines, found 1

原因在于pep 8规范,在声明函数的那一行的上方必须有两行的空行

新建django项目,app名blog

django项目在创建时会生成一个templates文件夹,用于存放html文件

templates新建index.html,内容随便输点

配置url:

首先views.py定义一个函数(使用render方法渲染html)

def index(request):

return render(request, 'index.html')

然后urls.py,导入views调用函数,配置url

from django.contrib import admin

from django.urls import path

import blog.views

urlpatterns = [

path('admin/', admin.site.urls),

path('blog/', blog.views.index)

]

配置项目的urls.py文件

从Django2.0开始,urls.py配置方法有很大改变。

把url函数换成了path,且不用写^$正则了

https://blog.csdn.net/qq_40272386/article/details/78800507

超链接

在django的templates模板中,需要将a标签的href内容写成这样:

{% url '项目名:应用名' param %}

项目名和应用名都是配置urls时的最后一个参数,

项目名是参数namespace(在include里),应用名是参数name

参考:https://blog.csdn.net/qq_33867131/article/details/81949022

urls.py 添加参数name

from django.contrib import admin

from django.urls import path

import blog.views

urlpatterns = [

path('admin/', admin.site.urls),

path('blog/', blog.views.index, name='blog'),

path('txt/<int:article_id>/', blog.views.article_page, name='txt'),

]

index.html {% url '项目名:应用名' param %}

如果传入了参数,就要写param(如这里是点击博客标题跳转到内容,在views.py里def函数传入了参数),只是简单的跳转就不用写

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>主页面</title>

</head>

<body>

{% for article in articles %}

<a href="{% url 'txt' article.id %}">{{ article.title }}</a><br>

{% endfor %}

</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_42490528/article/details/84038102