如何在Django中制作删除按钮

时间:2017-09-01 15:01:32

标签: python django

请帮助我了解如何删除按钮,必须删除Cat

class Cat(models.Model):
    class Meta():
        db_table = "cat"

    paw = models.IntegerField(default=4)
    name = models.CharField(max_length=30, null=False, default='Cat')
    age = models.IntegerField(default=False, null=False)
    species = models.CharField(max_length=50, blank=True)
    hairiness = models.IntegerField(default=False, null=False)

    def __str__(self):
        return self.name

这是我views.py,希望你能提供帮助。 (周一需要面试)

from django.shortcuts import render, get_object_or_404
from .models import Cat
from .forms import CatForm
from django.shortcuts import redirect

def home(request):
    template = "base.html"
    queryset = Cat.objects.all()
    context = {
        "object_list": queryset
    }
    return render(request, template, context)

def new_cat(request):
    if request.method == "POST":
        form = CatForm(request.POST)
        if form.is_valid():
            cat = form.save(commit=False)
            cat.save()
            return redirect('/', pk=cat.pk)
    else:
        form = CatForm()
    return render(request, 'new_cat.html', {'form': form})

def cat_edit(request, pk):
    cat = get_object_or_404(Cat, pk=pk)
    if request.method == "POST":
        form = CatForm(request.POST, instance=cat)
        if form.is_valid():
            cat = form.save(commit=False)
            cat.save()
            return redirect('/', pk=cat.pk)
    else:
        form = CatForm(instance=cat)
    return render(request, 'new_cat.html', {'form': form})

网站是asc添加更多细节,但我只是不知道还有什么,我可以添加。

from django.conf.urls import url
from . import views


urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^new/$', views.new_cat, name='new_cat'),
    url(r'^edit/(?P<pk>[0-9]+)/$', views.cat_edit, name='cat_edit'),
]

1 个答案:

答案 0 :(得分:5)

首先,您应该创建一个cat_delete视图,该视图应如下所示:

def cat_delete(request, pk):
    cat = get_object_or_404(Cat, pk=pk)  # Get your current cat

    if request.method == 'POST':         # If method is POST,
        cat.delete()                     # delete the cat.
        return redirect('/')             # Finally, redirect to the homepage.

    return render(request, 'template_name.html', {'cat': cat})
    # If method is not POST, render the default template.
    # *Note*: Replace 'template_name.html' with your corresponding template name.

然后,您应该在urls.py

中映射此视图
from django.conf.urls import url
from . import views

app_name = 'cats'
# Note that app_name is added here!
# It is used as a namespace in order to reverse your urls better.
# See usage in template.

urlpatterns = [
    # ...
    url(r'^delete/(?P<pk>[0-9]+)/$', views.cat_delete, name='cat_delete')
]

在您的模板中,您应该使用删除按钮创建一个表单,只需将 POST 请求发送到删除视图:

<form action="{% url 'cats:cat_delete' cat.id %}" method="post">
    {% csrf_token %}
    <input type="submit" value="Delete cat">
</form>

仔细查看表单的操作

{% url 'cats:cat_delete' cat.id %}

此处我使用的是app_name我之前添加的urls.py,以便按名称解析您的网址,而不是路径。现在cats:cat_delete将评估为cats/delete/<pk>。当然,你通过cat.id

这应该可以删除Cat模型的实例。希望我帮忙。