在为具有related model
的模型实现DeleteView时遇到问题。当我尝试删除Task对象时,什么也没有发生,并且它没有重定向到success_url
。注意发生。它只是继续显示模板。
这是型号:
class Project(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
date_created = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Task(models.Model):
name = models.CharField(max_length=50, default='New Model')
project = models.ForeignKey(Project, on_delete=models.CASCADE)
date_created = models.DateTimeField(default=timezone.now)
这是我的DeleteView类:
class TaskDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Task
template_name = 'tasks/confirm_delete.html' # template for deletion
success_url ='/projects/'
# Test user permission
def test_func(self):
task = self.get_object()
if self.request.user == task .project.author:
return True
else:
return False
def get_success_url(self):
project = self.object.project
return reverse_lazy('tasks-listview', kwargs={'pk': project.id })
和我的网址格式:
urlpatterns = [
path('tasks/<int:pk>/list/', TasksListview.as_view(), name='tasks-listview'),
path('tasks/<int:pk>/delete/', TaskDeleteView.as_view(), name='task-delete'),
]
这是我的删除庙宇:
<form method=" POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class='form-group'>
<h4>Current Project: {{ object.project }}</h4>
<h4>Are you sure you want to delete task named {{ object.name }}? </h4>
</fieldset>
<div class="form-group">
<button class="btn btn-danger float-sm-right mr-1" type="submit">Yes, Delete</button>
<a class="btn btn-secondary float-sm-right mr-1" href="{% url 'task-detail' object.id %}">Cancel</a>
</div>
</form>
答案 0 :(得分:0)
我的删除视图类包含:
def delete(self, request, *args, **kwargs):
self.get_object().delete()
messages.add_message(self.request, messages.SUCCESS, 'Entity removed with success.')
data = {'valid': True}
return JsonResponse(data)