Python 未在Django中加载注释

Python 未在Django中加载注释,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我做了很多实验,感觉很不对劲。我无法显示现有评论(我通过管理页面添加了一些评论)或评论表单。我试着用谷歌搜索这个问题并重新排列我的代码。不幸的是,我根本不知道是什么导致了这个问题。所以我不知道我的实验是否有一点是正确的 发布原始问题后,我尝试在代码中使用dispatch()。我收到了一些错误信息,我试着用谷歌搜索,但我只是试着在创可贴上面贴上创可贴 post_detail.html {% extends "blog/base.html" %} {% block content %} &l

我做了很多实验,感觉很不对劲。我无法显示现有评论(我通过管理页面添加了一些评论)或评论表单。我试着用谷歌搜索这个问题并重新排列我的代码。不幸的是,我根本不知道是什么导致了这个问题。所以我不知道我的实验是否有一点是正确的

发布原始问题后,我尝试在代码中使用dispatch()。我收到了一些错误信息,我试着用谷歌搜索,但我只是试着在创可贴上面贴上创可贴

post_detail.html

{% extends "blog/base.html" %}
{% block content %}
  <article class="media content-section">
    <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="#">{{ object.author }}</a>
        <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
        {% if object.author == user %}
          <div>
            <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
            <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
          </div>
        {% endif %}
      </div>
      <h2 class="article-title">{{ object.title }}</h2>
      <p class="article-content">{{ object.content }}</p>
    </div>
  </article>



  <article class="media content-section">
        <!-- comments -->
         <h3>{{ comments.count }} Comments</h3>
        {% for comment in comments %}

        <div class="media-body">
            <a class="mr-2" href="#">{{ comment.name }}</a>
            <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small>
        </div>
        <h2 class="article-title">{{ object.title }}</h2>
        <p class="article-content">{{ comment.body | linebreaks }}</p>

        {% endfor %}
  </article>



{% endblock content %}
型号.py

   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


from .forms import CommentForm
from django.shortcuts import render, get_object_or_404


def home(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/home.html', context)


class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']


#class PostDetailView(DetailView):
#    model = Post





class PostDetailView(DetailView):
    model = Post

    def dispatch():
        post = get_object_or_404(Post)
        comments = post.comments.filter(active=True, slug=slug)
        new_comment = None

        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                new_comment = comment_form.save(commit=False)
                new_comment.post = post
                new_comment.save()
            else:
                comment_form = CommentForm()
                return render(request, post_detail.html, {'post': post,
                                           'comments': comments,
                                           'new_comment': new_comment,
                                          'comment_form': comment_form})


class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)



class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


def about(request):
    return render(request, 'blog/about.html')
from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')
  from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse


# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=100)
    content =  models.TextField()
    date_posted = models.DateTimeField(default=timezone.now())
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    url= models.SlugField(max_length=500, unique=True, blank=True)

    def save(self, *args, **kwargs):
        self.url= slugify(self.title)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title 

    def get_absolute_url(self):
        return reverse('article_detail', kwargs={'slug': self.slug})


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_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

def __str__(self):
    return 'Comment {} by {}'.format(self.body, self.name)
url.py(在博客应用程序中)


更正代码的缩进

class PostDetailView(DetailView):
    model = Post

    def post_detail(request, slug):
        post = get_object_or_404(Post, slug=slug)
        comments = post.comments.filter(active=True)
        new_comment = None
        # Comment posted
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                # Create Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()
        else:
            comment_form = CommentForm()

        return render(request, template_name, {'post': post,
                                               'comments': comments,
                                               'new_comment': new_comment,
                                               'comment_form': comment_form})

更正代码的缩进

class PostDetailView(DetailView):
    model = Post

    def post_detail(request, slug):
        post = get_object_or_404(Post, slug=slug)
        comments = post.comments.filter(active=True)
        new_comment = None
        # Comment posted
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                # Create Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()
        else:
            comment_form = CommentForm()

        return render(request, template_name, {'post': post,
                                               'comments': comments,
                                               'new_comment': new_comment,
                                               'comment_form': comment_form})

你也可以分享你的模型吗?我现在已经在我的原始帖子底部添加了它们。你有关于
active=True
的评论吗?你能试着只使用
post.comments.all()
而不是
post.comments.filter()
检查一次吗?不幸的是,这没有什么区别。问题是你的
post\u detail()
方法从未被调用-这不是基本
DetailView
所寻找的方法。可能有助于查看
DetailView
的功能。您需要覆盖
dispatch()
方法,并将当前在
post\u detail()
中的逻辑放在那里。您也可以共享您的模型吗?我现在已将它们添加到我的原始帖子底部。您对
active=True
有评论吗?你能试着只使用
post.comments.all()
而不是
post.comments.filter()
检查一次吗?不幸的是,这没有什么区别。问题是你的
post\u detail()
方法从未被调用-这不是基本
DetailView
所寻找的方法。可能有助于查看
DetailView
的功能。您需要重写
dispatch()
方法,并将当前位于
post\u detail()
中的逻辑放在那里。
class PostDetailView(DetailView):
    model = Post

    def post_detail(request, slug):
        post = get_object_or_404(Post, slug=slug)
        comments = post.comments.filter(active=True)
        new_comment = None
        # Comment posted
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                # Create Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()
        else:
            comment_form = CommentForm()

        return render(request, template_name, {'post': post,
                                               'comments': comments,
                                               'new_comment': new_comment,
                                               'comment_form': comment_form})