Django博客新建文章

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/84675650

一 页面内容

  • 标题编辑栏

  • 文章内容编辑区域

  • 提交按钮

二 编辑响应函数

使用request.POST['参数名']获取表单数据

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

三  代码

1 index.html新增链接,链接到编辑页面

<!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>

2 urls.py新增编辑url和编辑提交url

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^index/$', 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'),
    url(r'^edit/action$', views.edit_action,name='edit_action'),
]

3 edit_page.html页面

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

4 views.py编辑以及编辑提交

from django.shortcuts import render
from django.http import HttpResponse
from . import models

def index(request):
    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})

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

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})

1 输入http://localhost:8000/blog/index/

2 点击新文章

3 编辑新文章

4 提交

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/84675650