在Django URL中找不到页面(404)

时间:2019-12-22 09:20:36

标签: django python-3.x django-templates django-views

这是我的views.py

def delete(request, id):
    employee = User.objects.get(id=id)
    employee.delete()
    return redirect('show')

这是我的urls.py

url(r'^delete/<int:id>', core_views.delete),

这是models.py

from django.db import models
class Employee(models.Model):
    eid = models.CharField(max_length=20)
    ename = models.CharField(max_length=100)
    eemail = models.EmailField()
    econtact = models.CharField(max_length=15)
    class Meta:
        db_table = "employee"

3 个答案:

答案 0 :(得分:0)

按如下所示纠正网址

url(r'^delete/<int:id>/$', core_views.delete),

也如下图所示更改视图

def delete(request, id):
    instance = get_object_or_404(Employee, id=id)
    instance.delete()
    return redirect('show')

答案 1 :(得分:0)

请不要在视图脚本中使用 delete()作为自定义方法名称

from django.shortcuts import render, redirect
from .models import Employee

def deleteAction(request, pk):
    employee = Employee.objects.get(pk=pk)
    employee.delete()
    return redirect('show')

答案 2 :(得分:0)

您不是要删除Employee对象,而是要删除User对象,这根本不是一回事。也许您忘记将user链接为OneToOneField了?

最简单的方法是使用基于类的视图,在您的情况下为DeleteView

from django.views.generic import DeleteView
from django.urls import reverse_lazy
from models import Employee

class DeleteEmployee(DeleteView):
   model = Employee
   success_url = reverse_lazy('show')

在您的urls.py中:

urlpatterns = [
    # [...]
    path('delete', views.DeleteEmployee.as_view(), name='delete_employee'),
]

请注意,我使用的是path而不是url,在这里不用正则表达式就更容易使用了。