博客撰写页面需要有:
- 文章标题输入框
- 文章内容输入框
- 提交按钮
这需要html知识,可以用1个form搞定。新建个edit_page.html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Page</title>
</head>
<body>
<form action="" method="post">
<label>文章标题
<input type="text" name="Title"/>
</label>
<br/>
<label>文章标题
<input type="content" name="content"/>
</label>
<br/>
<input type="submit" value="提交">
</form>
</body>
</html>
然后编辑views.py,建立响应函数以显示编辑页面
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'),
]
然后要把编辑的文章内容、标题写入数据库。标题和内容存储在响应函数收到的参数request.POST中。request.POST返回一个字典,而字典的get方法dict.get(key,default)意思是调用键为key的值,如果不存在则返回default。在views.py里创建个新的响应函数,接受在点了提交后收到的请求,把标题内容保存到数据库,响应出博客主页面。
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”的数据。
models.Article.objects.create(title=title,content=content)
这行代码里,models即为数据库的模板,create方法接受title和content两个字段,创建数据库里新的一行。
然后给“新文章”加超链接:
<!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>
网友评论