I’m having an issue that popped up with a Class Based View’s generic.DeleteView.
When I attempt to delete an instance of an object, I get the following error:
The view clients.views.view didn’t return an HttpResponse object. It returned None instead.
This is my delete class:
class CSNDelete(UserAccessMixin, SuccessMessageMixin, generic.DeleteView):
permission_required = 'clients.delete_csn'
model = CSN
form_class = CSNForm
template_name = 'generic_delete.html'
success_message = model._meta.verbose_name + " deleted successfully."
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(CSNDelete, self).get_context_data(**kwargs)
# Grab the single client id passed in from urls.py
client_id = self.kwargs['client_id']
context['c_id'] = client_id
context['client_full_name'] = get_object_or_404(Client, id=client_id)
return context
def form_valid(self, form):
obj = self.get_object()
messages.success(self.request, self.success_message % obj.__dict__)
return super(CSNDelete, self).delete(request, *args, **kwargs)
def form_invalid(self, form):
print('==> ERRORS: ' + str(form.errors))
# def delete(self, request, *args, **kwargs):
# obj = self.get_object()
# messages.success(self.request, self.success_message % obj.__dict__)
# return super(CSNDelete, self).delete(request, *args, **kwargs)
def get_success_url(self):
return reverse('clients:detail', args=[str(self.object.client.pk)])
And the heart of my delete template:
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
<h4 class="my-3">Are you sure you want to permanently delete "{{ object }}" from {{ client_full_name }}?</h4>
<button class="btn btn-danger">DELETE</button>
<a href="{{ view.get_success_url }}" class="btn btn-light">Cancel</a>
</form>
I was previously using the commented out “delete” method in the DeleteView, but saw on another post that I should be using the “form_valid” method.
I believe that the “form_valid” method is now causing another error when I try to delete the instance, saying that a specific field is required.
The field that it is saying is required looks like this in the models.py file:
goals = models.ManyToManyField("Obj2", verbose_name="Goals")
This is a new field that I added recently, after the original instance I’m trying to delete was created. Is that why this is having an issue? What is the best way to resolve this? Put some sort of default value on that ManyToManyField?
Or would I just need edit every instance that needs to be deleted and give it a value in that “goals” field first?
Or is there an if/else that needs to go in the form_valid method to “ignore” validation when using “Delete”?