hi ive read some of similar posts but couldn't find same problem. i wrote a code to delete post and when i press delete it shows 404 error but when back to home post is still there views:
def delete_music_view(request,music_id):
# view for deleting music
my_object = add_music.objects.get(id=music_id)
if request.method == 'POST':
my_object.delete()
return redirect('pages:home')
context = {'my_object':my_object}
return render(request,'pages/delete_music.html',context)
url:
urlpatterns = [
path('',views.home,name='home'),
path('add_music/',views.add_music_view,name='add_music'),
path('musics/<int:music_id>',views.musics_view,name='music_page'),
path('musics/<int:music_id>/delete',views.delete_music_view,name='delete_music'),
]
template:
{% extends 'pages/base.html' %}
{% block content %}
<form action="." method='POST'>
{% csrf_token %}
<p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p>
</form>
{% endblock %}
can u pls tell me whats wrong?
CodePudding user response:
Since the delete_music_view
method is going to handle the POST
request there's no need to use the form attribute action
. You have:
<form action="." method='POST'>
{% csrf_token %}
<p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p>
</form>
Remove the action
from your form and have this instead:
<form method='POST'> # Removing the action attribute
{% csrf_token %}
<p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p>
</form>
That should work.
Also, note that <a href="../../">cancel</a>
will show you another 404 error
if you don't set a recognizable url
for django
to handle.
I hope this answer helps.