博客頁(yè)面需要的功能:
- 在頁(yè)面上顯示博文標(biāo)題,是超鏈接
- 有個(gè)發(fā)表新文章的超鏈接按鈕
在網(wǎng)頁(yè)前端展示所有文章標(biāo)題需要用到for循環(huán)。
{%for XX in XXS%}
{%endfor%}
在模板里用這樣的格式
views.py里要獲取所有的文章,就不用get()了,改用all(),返回一個(gè)類似列表的對(duì)象。
views里:
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def index(request): #接受請(qǐng)求,做出響應(yīng)
articles = models.Article.objects.all()
return render(request,'blog/index.html',{'articles':articles})
html文件中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
<a href="">新文章 </a>
</h1>
{% for article in articles %}
<a href="">{{ article.title}}</a>
<br/>
{% endfor %}
</body>
</html>
文章頁(yè)需要展示標(biāo)題和內(nèi)容,之前已經(jīng)實(shí)現(xiàn),現(xiàn)在關(guān)鍵在于配置url,文章唯一的標(biāo)識(shí)是id號(hào),url里需要包含該id。views里的響應(yīng)函數(shù)也需要這個(gè)參數(shù)以確定該響應(yīng)哪篇文章。于是需要了解正則表達(dá)式的知識(shí):
(?P<name>...) 分組的命名模式,取此分組中的內(nèi)容時(shí)可以使用索引也可以使用name
https://www.cnblogs.com/dyfblog/p/5880728.html
urls.py里:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^article/(?P<article_id>[0-9]+)$',views.article_page),
]
(?P<article_id>[0-9]+)中:
[0-9]+意思是,0-9里的數(shù)字任意多個(gè)
(?P<article_id>...)意思是匹配了...里的正則表達(dá)式后保存為名為article_id的子組以供之后調(diào)用。
views里:
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def index(request): #接受請(qǐng)求,做出響應(yīng)
articles = models.Article.objects.all()
return render(request,'blog/index.html',{'articles':articles})
def article_page(request,article_id):
article = models.Article.objects.get(pk=article_id)
return render(request,'blog/article_page.html',{'article':article})
收到請(qǐng)求后,urls.py里的正則表達(dá)式會(huì)找出網(wǎng)址里的article_id傳遞給響應(yīng)函數(shù),這樣響應(yīng)函數(shù)就知道該響應(yīng)那篇文章了。
然后再做個(gè)文章頁(yè)面的模板article_page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>article_page</title>
</head>
<body>
<h1>{{ article.title}}</h1>
<br/>
<h3>{{ article.content}}</h3>
<br><br/>
<a href="">修改文章</a>
</body>
</html>