删除对象,从ListView到DeleteView

时间:2018-08-14 19:56:44

标签: django django-views

我有一个ListView,从中我想使用DeleteView删除一些对象。我到目前为止所拥有的:

views.py

class BlockListView(ListView):
    model= Classroom

    def get_context_data(self, **kwargs):
        context = super(BlockListView, self).get_context_data(**kwargs)
        classroom_blocks = Classroom.objects.all()
        context = {'classroom_blocks': classroom_blocks}
        return context

list_classroom_view = BlockListView.as_view()

class BlockDeleteView(DeleteView):
    model = Classroom
    success_url = reverse_lazy('classroom:blocklist')

delete_classroom_view = BlockDeleteView.as_view()

urls.py

urlpatterns = [
    path(r'^$', views.index, name='index'),
    path('submitted', views.submitted, name='submitted'),
    path('classup/', create_classroom_view, name='classroom'),
    path('block/', views.block, name='block'),
    path('blocklist/', list_classroom_view, name='blocklist'),
    path(r'^(?P<pk>\d+)/blockDelete/$', delete_classroom_view, name='blockDelete'),
]

用于列表视图的模板:

{% for block in classroom_blocks %}
    <li>{{ block.get_course_block_display }}<a href ="{% url 'classroom:blockDelete' block.id %}" class="button" style="color:#999999">DELETE</a></li>
{% empty %}
    <li>No classes set up yet.</li>
{% endfor %}

确认删除模板:

{% block body %}
<h1>Confirm Delete</h1>
<form action="." method="post">{% csrf_token %}
    <p>Are you sure you want to delete "{{ object.course_block }}"?</p>
    <input type="submit" value="Confirm" />
</form>
{% endblock %}

从列表视图中单击删除按钮后,生成的URL为http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/$,这将指向确认删除页面。确认删除后,我收到Request URL: http://127.0.0.1:8000/classroom/%5E(%3FP89%5Cd+)/blockDelete/

的404错误

1 个答案:

答案 0 :(得分:1)

您正在使用path(),因此您不应该使用正则表达式。将第一个和最后一个URL模式更改为:

path('', views.index, name='index'),
...
path('<int:pk>/blockDelete/', delete_classroom_view, name='blockDelete'),

现在,当您从列表视图中单击删除按钮时,应该将您带到/classroom/1/blockDelete/之类的网址,并且提交表单时也不会出现404错误。