#python #django #django-views
Вопрос:
Я получил error
сообщение при нажатии [Delete]
опции/ссылки в post_detail.html
:
Page not found (404)
No comment found matching the query
Request Method: GET
Request URL: http://127.0.0.1:8000/post/7/comment/delete/
Raised by: blog.views.CommentDeleteView
Вот мои файлы:
post_detail.html
файл
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{% if not post.comments.all %}
No Comments Yet...
<a href="{% url 'post-comment' post.pk %}">Add Comment</a>
<br/><br/><br/><br/><br/><br/>
{% else %}
<a href="{% url 'post-comment' post.pk %}">Add Comment</a>
<br/><br/>
{% for comment in post.comments.all %}
<strong>
{{user}},
</strong>
<small>
{{comment.date_added}}
</small>
<br/>
{{comment.body}}
<br/>
{% if request.user == user %}
<a href="{% url 'comment-delete' post.pk %}">[Delete]</a>
{% endif %}
<br/><br/>
{% endfor %}
{% endif %}
{% endblock content %}
models.py
файл
from django.db import models
from django.urls.base import reverse_lazy
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Comment(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(default=timezone.now)
date_added = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Meta:
ordering = ['-date_added']
views.py
файл
from django.contrib.messages.api import success
from django.urls.base import reverse_lazy
from users.forms import CommentForm
from django import forms
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Post, Comment
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
class AddCommentView(LoginRequiredMixin,CreateView):
model = Comment
form_class = CommentForm
template_name = 'blog/add_comment.html'
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
def get_success_url(self):
pk = self.kwargs['pk']
return reverse_lazy('post-detail', kwargs={'pk': pk})
class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Comment
template_name = 'blog/comment_delete.html'
def get_success_url(self):
pk = self.kwargs['pk']
return reverse_lazy('post-detail', kwargs={'pk': pk})
def test_func(self):
comment = self.get_object()
return self.request.user == comment.author
comment_delete.html
файл
{% extends "blog/base.html" %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Post</legend>
<h2>Are you sure you want to delete the post comment</h2>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-danger" type="submit">Delete</button>
<a class="btn btn-outline-secondary" href="{% url 'post-detail' object.id %}">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
urls.py
файл
from django.urls import path
from .views import (
AddCommentView,
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
CommentDeleteView,
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/comment/delete/', CommentDeleteView.as_view(), name='comment-delete'),
path('post/<int:pk>/comment/', AddCommentView.as_view(), name='post-comment'),
path('about/', views.about, name='blog-about'),
]
Комментарии:
1.
reverse_lazy('post-detail', kwargs={'pk': pk})
— после удаления вы перенаправляетесь на тот же удаленный пк?2. @bdbd Но если
[Delete]
ссылка не работает, как удаляется «pk»?3. Я думаю, что происходит то, что он успешно удаляет объект, затем перенаправляет на детализацию сообщения с пк, который вы только что удалили, но этот объект уже исчез, отсюда 404