使用外键删除对象时找不到 Django 页面(1 到多)

Django page not found when deleting object with foreign key (1 to many)

这是我第一次尝试使用外键删除对象。这些模型具有一对多关系:

class NumObject(models.Model):
    title= models.CharField(max_length=50)
    number= models.IntegerField()
    ident= models.IntegerField()
    usersave= models.CharField(max_length=100, blank= True)


    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        super(NumObject,self).save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('posts:detail', kwargs={'id': self.id})

class Sounds(models.Model):
    numobj = models.ForeignKey(NumObject)
    title = models.CharField(max_length=50)
    sound = models.FileField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('posts:detail', kwargs={'title': self.title})

NumObject 和 Sounds 的视图如下所示:

def post_detail(request,id= None):
    instance= get_object_or_404(NumObject, id=id)

    context= {
        'title': instance.number,
        'instance': instance,



}
    return render(request,'post_detail.html',context)

def sound_detail(request,id= None):
    instancesound= get_object_or_404(Sounds, id=id)


    context= {
        'sound': instance.number,
        'instancesound': instancesound,
}
    return render(request,'sound_detail.html',context)

在我的模板中,我可以显示与 "NumObject" 对象关联的所有 "Sounds" 对象:

{% for obj in instance.sounds_set.all %}
{% include 'sound_detail.html' %}    
{% endfor %}

sound_detail.html 有一个显示所有声音对象的 ul,还有一个 link 到每个声音对象的删除视图:

<a href="/{{instance.id}}/delete/">Delete</a>

删除视图的 url 如下所示:

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

删除视图:

def post_delete(request, id):
    sound= get_object_or_404(Sounds, pk=id).delete()

    return redirect('posts:list')

出于某种原因,当我尝试删除单个 "Sounds" 对象时,我得到 "Page not found" 以及 http://127.0.0.1:8000/8/delete/ 的请求 URL 和一个错误 "No Sounds matches the given query."(我觉得还不错)。在最困难的时候试图了解发生了什么,我们将不胜感激!

我认为 8 是错误的 ID。它是 NumObject id 而不是 Sounds id。您没有将 sounds_set 传递到 sounds_detail.html 页面。

尝试以下操作:

1) 更改您的模板以包含 sound_detail 和传递的变量:

{% include 'sound_detail.html' with sound=obj %}

2) 在 sound_detail 页面上,将 link 更改为:

<a href="/{{sound.id}}/delete/">Delete</a>

如果可行,请告诉我!