Reputation: 589
I want to delete an object via clicking on a glyphicon wrapped in a form. To do this, my function looks like this:
def deleteHabit(request, id):
print('deleteHabit')
habit_to_delete = get_object_or_404(Habit, id=id)
print(habit_to_delete)
if (request.method == 'POST'):
form = HabitForm(instance=habit_to_delete)
if form.is_valid(): # checks CSRF
print('delete') # normally habit_to_delete.delete()
return redirect('renderOverview') # wherever to go after deleting
else:
# Not Working
return render(request, 'overview/habit_delete_confirm', args)
My understanding of Post and Get is the 'Post' condition does roughly the deleting part and the 'Get' condition renders a confirmation page for example to confirm the deletion. However, the object will be deleted, but by clicking the form it redirects to success_url and does not show a confirmation page. What's wrong on the code snippet above?
Upvotes: 0
Views: 1348
Reputation: 589
Sry for answering this question so late, but I'm very busy atm. Another reason why I did'nt answer was that your answer is not the answer I was looking for. You can handle a CRUD operation either by a function (see above) or with a generic view (as you suggested). My function above was not correctly in more than one cases, but in question case, I did not get confirmation page, which means, I didn't get the 'GET REQUEST'. So, my mistake was not the function, but rather the correct url mapping.
Independently I'm using a DeleteView for now.
in views.py:
class HabitDeleteView(DeleteView):
model = Habit
success_url = reverse_lazy('display_habits')
in urls.py:
url(r'^habit/(?P<pk>\d+)/delete$', habits_views.HabitDeleteView.as_view(), name='delete_habit'),
in template I'm using this:
<a href="{% url 'delete_habit' habit.pk %}">
<span class="glyphicon glyphicon-trash custom-trash-habit-detail"></span>
</a>
Upvotes: 0