前面我们讲到了在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) 直接使用添加文章时的form表单。将需要修改的文章数据展示到前端。redirect函数返回到修改后的文章页面去了,因此需要同时把文章的id参数传递过去。 数据展示层(templates) 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 %} 和之前所说的当登陆用户为作者时,则显示编辑按钮。运行本地服务器,就实现了更新功能,我们可以看到,最后的更新时间
现在一个博客系统的基本功能都已经实现了,增删改查。