Django中的删除功能不起作用

时间:2018-02-21 08:01:31

标签: python django django-views

我正在尝试为我的Workout模型创建一个删除功能。 这是模型:

class Workout(models.Model):
    workoutID = models.AutoField(primary_key=True)
    name = models.CharField(max_length=40)
    created_by = models.ForeignKey(User)
    description = models.TextField()   
    created_at = models.DateTimeField(auto_now_add=True)

    def delete(self):
        return reverse("delete_workout", kwargs = {'workout_id': self.workoutID})

接下来我有了观点:

def delete_workout(request, workout_id):
    workout = get_object_or_404(Workout, workoutID = workout_id)
    print(workout)
    if request.user != workout.created_by:
        return HttpResponse('Not ur workout')
    else:
        workout.delete()
        return HttpResponseRedirect('/')

这是网址:

url(r'^(?P<workout_id>\d+)/delete/$', views.delete_workout, name='delete_workout'),  

最后是html:

<a href='{{ instance.delete }}'>
    <button>Delete Workout</button> 
</a>

我在控制台中没有出现任何错误,这就是为什么我不知道出了什么问题。

2 个答案:

答案 0 :(得分:1)

您只是为了获取删除网址而重写该类的删除方法。您将通过模板中的url函数获取网址,例如{% url delete_workout instance.workoutID %}。因此从模型中删除删除功能会更改您的html href url。保持视图和网址相同。没有问题

类应

class Workout(models.Model):
    workoutID = models.AutoField(primary_key=True)
    name = models.CharField(max_length=40)
    created_by = models.ForeignKey(User)
    description = models.TextField()   
    created_at = models.DateTimeField(auto_now_add=True)

你的HTML应该是

<a href='{% url delete_workout instance.workoutID %}'>
    <button>Delete Workout</button> 
</a>

注意: django模型本身会为每个表添加id,因此您不必像workoutID = models.AutoField(primary_key=True)那样指定它。 默认情况下,每个模型都有一个id字段,就像id = models.AutoField(primary_key=True)

一样

如果您考虑删除workoutID,则模型将变为

class Workout(models.Model):
        name = models.CharField(max_length=40)
        created_by = models.ForeignKey(User)
        description = models.TextField()   
        created_at = models.DateTimeField(auto_now_add=True)

,html将是

<a href='{% url delete_workout instance.id %}'>
    <button>Delete Workout</button> 
</a>

答案 1 :(得分:0)

Django为您提供了所有工具。不要重新发明轮子。您可以重构和简化代码。

首先删除delete中的方法Workout

其次,用基于类的视图替换基于函数的视图:

from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from django.http import Http404

from .models import Workout

class WorkoutDeleteView(DeleteView):
    model = Workout
    success_url = reverse_lazy('delete_workout')

    def get_object(self):
        obj = super().get_object()
        if obj.created_by != self.request.user:
            raise Http404
        return obj

只能由作者删除锻炼。在success_url中,您可以指定删除后应重定向用户的目标。

只需稍微调整urls.py(注意强调部分):

url(r'^(?P<pk>\d+)/delete/$', views.WorkoutDeleteView.as_view(), name='delete_workout'),

编辑: 您可以根据需要为自己的观点命名,但最好遵循已经完善的惯例。因此,基于类的视图的名称应为workout-listworkout-detailworkout-createworkout-updateworkout-delete