13_修改文章

本文详细介绍了如何在Django中实现文章的更新功能。从增加路由、视图函数到前端模板的修改,逐步讲解了文章更新的完整流程。用户可以编辑并保存文章,完成后系统会重定向到更新后文章的详情页。此外,只有文章作者才能看到编辑按钮,确保了内容的安全性。
摘要由CSDN通过智能技术生成

修改文章

前面我们讲到了在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参数传递过去。
  1. 数据展示层(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获取修改后的内容进行保存更新。
  1. 修改文章入口
            {% 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 %}

  • 和之前所说的当登陆用户为作者时,则显示编辑按钮。

运行本地服务器,就实现了更新功能,我们可以看到,最后的更新时间

在这里插入图片描述

现在一个博客系统的基本功能都已经实现了,增删改查。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码是用来爬取新闻网站文章并保存到本地的,但是有一些问题需要修改。 1. 需要将导入 requests 和 bs4 的代码分别写在两行。 2. 在 url 变量中,链接中有空格,需要去除。 3. 在 range 函数中,第二个参数应该是 4580786,因为 range 函数不包括最后一个数。 4. 在写文件时,文件名应该为 f"{page_count + 1}.txt",而不是 f"{i}.txt",因为每一页可能会保存多篇文章。 5. 在爬取过程中,应该加上异常处理,防止程序因为网络连接问题而中断。 修改后的代码如下: ``` import requests from bs4 import BeautifulSoup import os import time headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15'} page_count = 0 for page_num in range(1,10000): for i in range(3579989,4580786): url = f"https://www.antaranews.com/berita/{i}/sekjen-puji-indonesia-selenggarakan-ktt-ke-42-asean-dengan-baik?utm_source=antaranews&utm_medium=desktop&utm_campaign=menu_news" try: res = requests.get(url, headers=headers) soup = BeautifulSoup(res.text, "html.parser") div = soup.find("div", {"class": "col-md-8"}) if not div: continue text = div.text file = f"{page_count + 1}.txt" with open(file, "w", encoding="utf-8") as f: f.write(text) print(f"{i} saved successfully.") page_count += 1 if page_count >= 500: break time.sleep(15) except Exception as e: print(f"Error occurred: {e}") continue if page_count >= 500: break print("All pages saved successfully.") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值