代码拉取完成,页面将自动刷新
前面我们讲到了在Django的增添、删除文章,现在我们在前端进行修改更新文章。
article/urls.py
path('update_art/<int:id>/', views.update_art, name='update_art'),
article/views.py
def update_art(request, id):
article = get_object_or_404(Article, id=id)
if request.method == 'POST':
article_update_form = ArticleAddForms(request.POST)
if article_update_form.is_valid():
data = article_update_form.cleaned_data
article.article_title = data['article_title']
article.article_context = data['article_context']
article.save()
# 修改完成,重定向到当前文章的详情
return redirect(reverse('article:article_detail', kwargs={'id': id, }))
else:
article_update_form = ArticleAddForms()
context = {
'article': article,
'article_update_form': article_update_form,
'msg': '编辑失败',
}
return render(request, 'update_art.html', context)
else:
article_update_form = ArticleAddForms()
context = {
'article': article,
'article_update_form': article_update_form,
}
return render(request, 'update_art.html', context)
templates/update_art.html
<!-- 提交文章的表单 -->
<form method="post" action=" ">
{% csrf_token %}
<!-- 文章标题 -->
<div class="form-group">
<!-- 标签 -->
<label for="title">文章标题</label>
<!-- 文本框 -->
<input type="text" class="form-control" id="title" name="article_title" value="{{ article.article_title }}">
</div>
<!-- 文章正文 -->
<div class=" form-group">
<label for="body">文章正文</label>
<!-- 文本区域 -->
<textarea type="text" class="form-control" id="body" name="article_context"
rows="12">{{ article.article_context }}</textarea>
</div>
<!-- 提交按钮 -->
<button type="submit" class="btn btn-primary">完成</button>
</form>
views.py
去理解,首先通过get请求,将文章的参数(标题和内容)传到前端,再通过POST获取修改后的内容进行保存更新。 {% if article.art_user == request.user %}
<a href="{% url 'article:update_art' article.id %}" class="btn btn-info" role="button">编辑</a>
<a href="#" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal" role=" button">删除</a>
<a href="#" class="btn btn-light" role="button">私密</a>
{% endif %}
运行本地服务器,就实现了更新功能,我们可以看到,最后的更新时间
现在一个博客系统的基本功能都已经实现了,增删改查。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。