# 更新文章
@login_required(login_url='/userprofile/login/')
def article_update(request, id):
"""
更新文章的视图函数
通过POST方法提交表单,更新title、body字段
:param request:
:param id: 文章的id
:return:
"""
article = ArticlePost.objects.get(id=id)
# 过滤非作者的用户
if request.user != article.author:
return HttpResponse('抱歉,你无权修改这篇文章。')
if request.method == 'POST':
article_post_form = ArticlePostForm(data=request.POST)
if article_post_form.is_valid():
article.title = request.POST['title']
article.body = request.POST['body']
if request.POST['column'] != 'none':
article.column = ArticleColumn.objects.get(id=request.POST['column'])
else:
article.column = None
article.tags.set(*request.POST['tags'].split(',')) #就是此行代码,非常重要
article.save()
# article_post_form.save_m2m()
return redirect('article:article_detail', id=id)
else:
return HttpResponse('表单内容有误,请重新填写。')
else:
article_post_form = ArticlePostForm()
columns = ArticleColumn.objects.all()
tags = article.tags.all()
tags = ','.join([tag.name for tag in tags])
context = {
'article': article,
'article_post_form': article_post_form,
'columns': columns,
'tags': tags
}
return render(request, 'article/update.html', context)
核心代码就是文中的article.tags.set(*request.POST['tags'].split(','))
这一句。