Nawal
Nawal

Reputation: 3

deleting an object in django

i want to delete a task from the database so i use this code this is my delete view

def task_Delete(request,id=None):
        if request.method == 'POST':
            form = TaskForm()
            id = int(request.POST.get('task.id'))
            task = Task.objects.get(id=id)
            task.delete()
            messages.success(request,"successfully delete")
            return render_to_response('home.html', {'form': form})

and that is my urls.py

url(r'^task_Delete/$', views.task_Delete, name='task_Delete')

this the code of the button delete :

<form action="{% url 'task_Delete' %}" method="post" >
               {% csrf_token %}
            <input type="hidden" name="task_id" value="{{task.id}}" />
               <input type="submit" value="delete task">
        </form></td>
  </tr>

when i click on delete nothing happend i don't know why , please help thanks in advance

Upvotes: 0

Views: 187

Answers (1)

Serafeim
Serafeim

Reputation: 15084

There are various problems in your code (for example the TaskForm is not needed at all) however if you change the line

id = int(request.POST.get('task.id'))

to

id = int(request.POST.get('task_id'))

the object will probably be deleted; remember that the request parameter's name will be the same as the name of the input (task_id). I recommend using proper CBVs (a DeleteView) for what you want to do - if you want a slow and comprehensive tutorial on that I recommend this article: https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/

Upvotes: 1

Related Questions