DEV Community

Phansivang
Phansivang

Posted on

Django Delete Post

views.py

from django.shortcuts import render, redirect,get_object_or_404
from .models import Post

def delete_view(request, id):
    obj = get_object_or_404(Post,id=id)
    if obj.author.id == request.user.id:
        if request.method == 'POST':
            obj.delete()
            return redirect("/")
        return render(request, "app/post_confirm_delete.html")
    return redirect('/')
Enter fullscreen mode Exit fullscreen mode

urls.py

from django.urls import path
from . import views

urlpatterns = [

    path('post/<int:id>/delete',views.delete_view,name='delete-post'),

]
Enter fullscreen mode Exit fullscreen mode

post_confirm.delete.html

{% extends 'app/main.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <form method="POST">
        {% csrf_token %}
        <h1>Are you sure?</h1>
        <button class="btn btn-outline-danger btn-sm mt-1" type="submit" value="Yes">Yes</button>
        <a class="btn btn-outline-info btn-sm mt-1" href="{% url 'home' %}">Cancel</a>
    </form>
{% endblock %}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)