简体   繁体   English

Django通过发布请求删除对象

[英]Django Delete an object via Post request

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. 我对Post and Get的理解是,“ Post”条件大致执行删除部分,而“ Get”条件则显示确认页面,例如,以确认删除。 However, the object will be deleted, but by clicking the form it redirects to success_url and does not show a confirmation page. 但是,该对象将被删除,但是通过单击表单,它会重定向到success_url,并且不会显示确认页面。 What's wrong on the code snippet above? 上面的代码段有什么问题?

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). 您可以通过函数(请参见上文)或通过通用视图(如建议的那样)来处理CRUD操作。 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. 我现在正在独立使用DeleteView。

in views.py: 在views.py中:

class HabitDeleteView(DeleteView):
    model = Habit
    success_url = reverse_lazy('display_habits')

in urls.py: 在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM