博客撰寫頁面需要有:
- 文章標(biāo)題輸入框
- 文章內(nèi)容輸入框
- 提交按鈕
這需要html知識(shí),可以用1個(gè)form搞定液茎。新建個(gè)edit_page.html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Page</title>
</head>
<body>
<form action="" method="post">
<label>文章標(biāo)題
<input type="text" name="Title"/>
</label>
<br/>
<label>文章標(biāo)題
<input type="content" name="content"/>
</label>
<br/>
<input type="submit" value="提交">
</form>
</body>
</html>
然后編輯views.py,建立響應(yīng)函數(shù)以顯示編輯頁面
def edit_page(request):
return render(request,'blog/edit_page.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, name='article_page'),
url(r'^edit$',views.edit_page, name='edit_page'),
]
然后要把編輯的文章內(nèi)容多搀、標(biāo)題寫入數(shù)據(jù)庫。標(biāo)題和內(nèi)容存儲(chǔ)在響應(yīng)函數(shù)收到的參數(shù)request.POST中蝌焚。request.POST返回一個(gè)字典移剪,而字典的get方法dict.get(key,default)意思是調(diào)用鍵為key的值,如果不存在則返回default瓤摧。在views.py里創(chuàng)建個(gè)新的響應(yīng)函數(shù)竿裂,接受在點(diǎn)了提交后收到的請(qǐng)求,把標(biāo)題內(nèi)容保存到數(shù)據(jù)庫照弥,響應(yīng)出博客主頁面腻异。
def edit_action(request):
title = request.POST.get('title','TITLE')
content = request.POST.get('content','CONTENT')
models.Article.objects.create(title=title,content=content)
articles = models.Article.objects.all()
return render(request,'blog/index.html',{'articles':articles})
這里request里包含了edit_page.html文件里的name為“title”和“content”的數(shù)據(jù)。
models.Article.objects.create(title=title,content=content)
這行代碼里这揣,models即為數(shù)據(jù)庫的模板悔常,create方法接受title和content兩個(gè)字段影斑,創(chuàng)建數(shù)據(jù)庫里新的一行。
然后給“新文章”加超鏈接:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
<a href="{%url 'blog:edit_page' %} ">新文章 </a>
</h1>
{% for article in articles %}
<a href="{% url 'blog:article_page' article.id %}">{{ article.title}}</a>
<br/>
{% endfor %}
</body>
</html>