編輯功能
編輯頁(yè)面:
- 打開(kāi)文件:
blog/templates/article/details.html
眯停,并修改:
<h2>{{ article_details.title }}</h2>
<h3>{{ article_details.content }}</h3>
<p>
<a href="{% url 'blog:article$index_page' %}">返回列表</a>
<a href="{% url 'blog:article$edit_page' article_details.id %}">修改</a>
</p>
- 修改:
blog/view/article.py
,添加如下方法:
# 編輯頁(yè)面
def edit_page(request, article_id='0'):
# 如果article_id == '0'办绝,則視為創(chuàng)建新文章
if article_id == '0':
return render(request=request, template_name='article/edit.html')
else:
article_details = models.article.Article.objects.get(pk=article_id)
return render(request=request, template_name='article/edit.html', context={'article_details': article_details})
- 創(chuàng)建模板文件:
blog/templates/article/edit.html
,并寫(xiě)入:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章詳情頁(yè):{{ article_details.title }}</title>
</head>
<body>
{% if article_details.id %}
<h2>修改文章</h2>
{% else %}
<h3>創(chuàng)建文章</h3>
{% endif %}
<form action="{% url 'blog:article$edit_action' %}" method="post">
{% csrf_token %}
<input type="hidden" name="article_id" value="{{ article_details.id | default:'0' }}">
<input type="text" name="article_title" value="{{ article_details.title }}">
<br>
<input type="text" name="article_content" value="{{ article_details.content }}">
<br>
<br>
<button>保存</button>
</form>
</body>
</html>
- 加入U(xiǎn)RL,修改
blog/url.py
:
url(regex=r'^article/edit/(?P<article_id>[0-9]+)/$', view=article.edit_page, name='article$edit_page'),
url(regex=r'^article/edit_action/$', view=article.edit_action, name='article$edit_action')
查看結(jié)果议薪,訪(fǎng)問(wèn):http://localhost:8000/blog/artilce/detials/1/
image
image
編寫(xiě)功能:
- 修改
blog/view/article.py
,加入edit_action方法:
# 保存編輯
def edit_action(request):
article_id = request.POST.get('article_id', 0)
article_title = request.POST.get('article_title')
article_content = request.POST.get('article_content')
if article_id == 0:
# 創(chuàng)建文章
article_model = models.article.Article(title=article_title, content=article_content)
try:
# 寫(xiě)入成功媳友,返回列表頁(yè)
article_model.save()
return index_page(request=request)
except Exception, e:
# 打印錯(cuò)誤
print(e)
else:
# 修改文章
article_details = models.article.Article.objects.get(pk=article_id)
article_details.title = article_title
article_details.content = article_content
try:
# 修改成功斯议,返回詳情頁(yè)面
article_details.save()
return details_page(request=request, article_id=article_id)
except Exception, e:
# 打印錯(cuò)誤
print(e)
查看結(jié)果,訪(fǎng)問(wèn):http://localhost:8000/blog/article/edit/1/
image
image
image
編寫(xiě)新建功能
- 修改
blog/templates/article/index.html
醇锚,并修改:
{#由于我們通過(guò)article_id是否為0哼御,視為修改或創(chuàng)建的標(biāo)簽,則在該URL中路由參數(shù)寫(xiě)0#}
<p><a href="{% url 'blog:article$edit_page' 0 %}">新建文章</a></p>