python - Django - 如何删除文章?

标签 python django

我正在尝试在 django 框架上创建一个按钮,让我可以删除博客上自己的文章。我尝试为此功能创建代码,但它不起作用。

views.py

if(request.GET.get('delete')):  #if the button is clicked
    delete_article = get_object_or_404(Article, id=id)

    if request.POST:
        form = DeleteNewForm(request.POST, request.FILES)

        if form.is_valid(): 
            delete_article.delete()
            return HttpResponseRedirect("/")

template.html

<form enctype='multipart/form-data' action="." method="post" class="form"  autocomplete="off" autocorrect="off">
    {% csrf_token %}
    <div class="form-group">TITRE
      {{ form.title.errors }}
      {{ form.title }}
    </div>
    <div class="form-group">CONTENU
      {{ form.media }}
      {{ form.contenu.errors }}
      {{ form.contenu }}
    </div>
    <div class="form-group">
      {{ form.image.errors }}
      {{ form.image }}
   </div>
   <input type="submit" class="btn btn-default" value="Edit Article"/>
   <input type="submit" class="btn btn-default" value="Delete Article" name="delete">
</form>

这是我提交表单时发生的情况:我没有在索引上重定向,因为它应该重定向我,并且该文章尚未被删除。

是否存在不允许我删除这些行中的文章的问题?

最佳答案

我不知道您在 View 或模板中做什么。但如果我想删除某些内容,我只需为此定义一个单独的 View 。

# views.py

from django.views.generic.base import View

class DeleteView(View):
    def post(self, request *args, **kwargs):
        article = get_object_or_404(id=request.POST['article_id'])
        # perform some validation, 
        # like can this user delete this article or not, etc.
        # if validation is successful, delete the article
        article.delete()
        return HttpResponseRedirect('/')

你的模板应该是这样的:

<form action="/url/to/delete/view/" method="POST">
    {% csrf_token %}
    <input type="hidden" value="{{ article.id }}">
    <input type="submit" value="Delete">
</form>

关于python - Django - 如何删除文章?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946306/

相关文章:

python - GAE webapp2 删除特定用户的所有 UserToken(删除所有 sessios)

python - 对 Django 通用 View 有点困惑

python - Python 中不同 Web 编程方法的优缺点

python - PySide QGLBuffer 分配输入数据

python - 类型错误 : 'AnonymousUser' object is not iterable

python - 如何将 django 中的多个字段添加到一起?

Python - 列表上的简单算法任务(求职面试的标准问题)

django - 适用于Django Web开发的IDE

django - 如何用SSL实现Nginx 'Service Unavailable'?

javascript - 从自动完成搜索表单访问数据