Django学习:添加文章页面(10)

来源:互联网 发布:淘宝双十一收货时间 编辑:程序博客网 时间:2024/04/28 05:09

博客中添加文章页面及响应

在template中添加add_article.html页面 (form label input)请求方法使用post

这个页面涉及到了两个响应函数 1)显示页面的响应函数 2)表单提交的响应函数

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>edit article</title></head><body><form action=" " method="post">    <label>文章标题        <input type="text" name="title" />    </label>    <p></p>    <label>文章内容        <input type="text" name="content" />    </label>    <p></p>    <input type="submit" value="提交"></form></body></html>

显示页面的响应函数

views.py

def add_page(request):    return render(request, 'blog/add_article.html')

urls.py

urlpatterns = [    url(r'^$', views.index),    url(r'^article/(?P<article_id>[0-9]+)$', views.page, name='page'),    url(r'^edit/$', views.add_page, name='add_page'),]

打开服务器 localhost:8000/blog/edit

表单提交的响应函数

在表单里填写的内容,浏览器通过HTTP请求传递到后台的时候,这些数据都会被写在请求中,因此后台代码接受表单数据的过程实际上就是接受HTTP请求中夹带数据的过程

编辑响应函数

使用 request.POST[' 参数名 '] 获取表单数据 (通过HTTP请求,传递的数据就放在request里,HTTP请求分为post,get等方法,request对不同方法创建了字典,用于存储数据,request.POST里面的键值对就是前端的数据)

取得数据之后,要放入数据库中(models类):

models.Article.objects.create(title,content)创建对象


views.py(return响应后的页面)

def edit_action(request):    title = request.POST.get('title','TITLE')    content = request.POST.get('content','CONTENT')    models.Article.objects.create(title=title,content=content)    arts = models.Article.objects.all()    return render(request, 'blog/index.html', {'articles': arts})

urls.py

urlpatterns = [    url(r'^$', views.index),    url(r'^article/(?P<article_id>[0-9]+)$', views.page, name='page'),    url(r'^edit/$', views.add_page, name='add_page'),    url(r'^edit/action$', views.edit_action, name='edit_action'),]


add_article.html中表单form的action添加

<form action="{% url 'blog:edit_action' %}" method="post">

打开服务器 localhost:8000/blog/edit

在表格中输入后,点击提交,页面会出现

禁止访问(403)

CSRF验证失败,响应中断


这是安全性问题,如果用post提交表单,要在form中加入 {% csrf_token %} 用于防范csrf(跨站请求伪造)

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>edit article</title></head><body><form action="{% url 'blog:edit_action' %}" method="post">    {% csrf_token %}    <label>文章标题        <input type="text" name="title" />    </label>    <p></p>    <label>文章内容        <input type="text" name="content" />    </label>    <p></p>    <input type="submit" value="提交"></form></body></html>

index.html中新文章加上url

<body><h1><a href="#">我的博客</a> </h1><h3><a href="{% url 'blog:add_page' %}">添加新文章</a> </h3>{% for wz in articles %}<a href="{% url 'blog:page' wz.pk %}">{{ wz.title }}</a><br/>{% endfor %}</body>

打开服务器 localhost:8000/blog, 点击添加新文章,完成文章标题和内容的填写,点击提交



1 0
原创粉丝点击