Home > database >  DeleteView lead to error 405 when submit is clicked on django
DeleteView lead to error 405 when submit is clicked on django

Time:06-14

I have this small blog post app where everything works fine apart from delete view. As soon as I hit delete button I'm moved to my delete post page but when I hit confirm from DeleteView html page I get 405 error

My views.py for delete looks like this:

class DeletePost(DetailView):
    model = Articles
    template_name = 'delete_article.html'
    success_url = reverse_lazy('list_articles')

My html file where the link is mentioned is like this:

<!DOCTYPE html>
{% extends 'base.html' %}

{% block body %}
<div >
{% for i in articles %}
    <div >
        <h2>{{i.title}}</h2>
        <p>- {{i.author}}</p>
        {{i.created_on}}
        {{i.updated_on}}
        <p>{{i.content}}</p>
        <a  href="{% url 'update_article' i.id %}">Update</a>
        <a  href="{% url 'delete_article' i.id %}">Delete</a>
    </div>
{% endfor %}
</div>
{% endblock %}   

urls.py looks this way:

from django.urls import path

from mysite import views

urlpatterns = [
    path('articles/', views.PostList.as_view(), name='list_articles'),
    path('articles/<pk>/', views.PostDetail.as_view(), name='detail_article'),
    path('create/new/', views.CreateNewPost.as_view(), name='create_new_article'),
    path('update/<pk>/', views.UpdatePost.as_view(), name='update_article'),
    path('delete/<pk>/', views.DeletePost.as_view(), name='delete_article'),
]

and html for DeleteView:

<!DOCTYPE html>
{% extends 'base.html' %}

{% block body %}
<form method="post">
    {% csrf_token %}
    <p>Are you sure you want to delete "{{ object }}"?</p>
    {{ form.as_p }}
    <input class='btn btn-danger' type="submit"  value="Confirm">
</form>
{% endblock %}

CodePudding user response:

You have mentioned DetailView for deletion which is not correct, mention DeleteView instead which is at from django.views.generic.edit import DeleteView.

Note: Class based views required actual view name as the suffix, so you should write it as PostDeleteView instead of DeletePost. Similarly, write PostListView, PostDetailView etc. Add model name as the prefix and view name as the suffix and must be in PascalCase.

CodePudding user response:

405 means method not allowed, change your form POST method to DELETE method.

<form method="DELETE">

  • Related