Reputation: 1918
I'm very very new to Django and I'm currently trying to build a simple To-Do application. I'm currently able to display my To-Do list on the webpage using HTML Tables, but to be able to delete it, I added a new row at the end of every entry called "Delete"
with an a href element, on click event
sending it to a JS function that pops up a confirmation to the user asking if he actually wants to delete it. I'm storing the response in a variable called response
. Now, my question is how do I send this response across django to actually be able to delete the entry? This is what I have done so far and its not working. All help will be appreciated. Thank You.
{% for item in task %}
<tr>
<td>{{ item.task_name }}</td>
<td>{{ item.task_priority }}</td>
<td>{{ item.task_status }}</td>
<td>{{ item.target_date }}</td>
<td><a href="" onclick="return delete_function()">Delete</a></td>
<p id="delete"></p>
</tr>
{% endfor %}
</table>
<script>
function delete_function() {
var response = confirm("Are you sure you want to delete this item?");
if (response == true){
response.post()
}
}
</script>
In my views page, I have this function to handle this post method:
def view_task(request):
if request.method == 'GET':
context = dict()
context['task'] = Task.objects.all()
return render(request, 'todo/view_tasks.html', context)
if request.method == 'POST':
task_name = request.post['task_name']
Task.objects.delete(task_name)
Task.objects.save()
What am I doing wrong? Also, could you also explain to me with your answer when and where should I use post and get or at least direct me to some very well answered questions about the same topic?
Upvotes: 1
Views: 540
Reputation: 338
I don't think that this would be a good way to solve the problem,
try to do this:
in your template.html:
<form method="POST" action="">
{% csrf_token %}
<input type="submit" name="delete_amount" onclick="delete_me(event)" />
</form>
in your view.py:
#just in case you have other form
if 'delete_amount' in request.POST:
# do your deleting query here
print('deleting amount')
and in your javascript.js:
<script>
function delete_me(e)
{
if(!confirm('Are you sure you want to delete this?')){
//prevent sending the request when user clicked 'Cancel'
e.preventDefault();
}
}
</script>
Hope this will help!
Upvotes: 2