添加了管理面板中的评论,但在网站上不可见

时间:2021-06-08 11:57:56

标签: python django django-models django-views django-comments

基于本教程https://www.youtube.com/watch?v=An4hW4TjKhE&ab_channel=AbhishekVerma 我正在尝试添加在帖子下添加评论的功能,在管理面板中添加评论,一切正常,但该网站在帖子下不显示任何内容

这里是models.py


    from django.db import models
    from django.urls import reverse
    from django.contrib.auth.models import User
    from django.contrib.contenttypes.models import ContentType
    
    
    class Post(models.Model):
        published = None
        title = models.CharField(max_length=200)
        author = models.ForeignKey(
            'auth.User',
            on_delete=models.CASCADE,
        )
        body = models.TextField()
        header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg')
    
        def __str__(self):
            return self.title
    
        def get_absolute_url(self):
            return reverse('post_detail', args=[str(self.id)])
    
    
    class Comment(models.Model):
    
        post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_post')
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_user')
        content = models.TextField(max_length=160)
        timestamp = models.DateTimeField(auto_now_add=True)
    
        def __str__(self):
            return '{}-{}'.format(self.post.title, str(self.user.username))

views.py


    from django.http import HttpResponseRedirect
    from django.shortcuts import render, get_object_or_404
    from django.views.generic import ListView, DetailView
    from django.views.generic.edit import CreateView, UpdateView, DeleteView
    from django.urls import reverse_lazy
    from .models import Post, Comment
    from django import forms
    from .forms import *
    
    
    class BlogListView(ListView):
        model = Post
        template_name = 'home.html'
    
        context_object_name = 'posts'
        paginate_by = 2
        queryset = Post.objects.all()
    
    class BlogDetailView(DetailView):
        model = Post
        template_name = 'post_detail.html'
    
    class BlogCreateView(CreateView):
        model = Post
        template_name = 'post_new.html'
        fields = ['title', 'author', 'body', 'header_image']
    
    class BlogUpdateView(UpdateView):
        model = Post
        template_name = 'post_edit.html'
        fields = ['title', 'body', 'header_image']
    
    class BlogDeleteView(DeleteView):
        model = Post
        template_name = 'post_delete.html'
        success_url = reverse_lazy('home')
    
    
    @property
    def image_url(self):
        """
        Return self.photo.url if self.photo is not None,
        'url' exist and has a value, else, return None.
        """
        if self.image:
            return getattr(self.photo, 'url', None)
        return None
    
    def post_detail(request, id, slug):
        post = get_object_or_404(Post, id=id, slug=slug)
        comments = Comment.objects.filter(post=post).order_by('-id')
        is_liked = False
        if post.likes.filter(id=request.user.id).exists():
            is_liked = True
    
        if request.method == 'POST':
            comment_form = CommentForm(request.POST or None)
            if comment_form.is_valid():
                content = request.POST.get('content')
                comment = Comment.objects.create(post=post, user=request.user, content=content)
                comment.save()
                return HttpResponseRedirect(post.get_absolute_url())
    
        else:
            comment_form = CommentForm()
    
        context = {
            'post': post,
            'is_liked': is_liked,
            'total_likes': post.total_likes(),
            'comments': comments,
            'comment_form': comment_form,
        }
        return render(request, 'myblog/post_detail.html', context) #his "blog" = my "myblog"
    
    class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ('content',)

post_detail.html


    {% extends 'base.html' %}
    
    {% block content %}
        <div class="post-entry">
            <h2>{{ post.title }}</h2>
            <p>{{ post.body }}</p>
        </div>
    
        <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p>
        <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p>
        <img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">
    
        {{ post.body|urlize }}
    
    
    
        {% for comm in post.commentpost_set.all%}
            {{ comm.user }} <br>
            {{ comm.text }} <br><br>
        {% endfor %}
    {% endblock content %}
    
    
    <br><br>
    <hr>
    
    <form method="post">
        {% csrf_token %}
        {{ comment_form.as_p }}
        {% if request.user.is_authenticated %}
            <input type="submit" value="Submit" class="btn btn-outline-success">
        {% else %}
            <input type="submit" value="Submit" class="btn btn-outline-success" disabled>
        {% endif %}
    </form>
    
    <div class="main-comment-section">
        {{ comments.count }} Comment{{ comments|pluralize }}
        {% for comment in comments %}
            <blockquote class="blockquote">
                <p class="mb-0">{{ comment.content }}</p>
                <footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
            </blockquote>
        {% endfor %}
    </div> 

myblog/urls.py


    from django.urls import path
    
    from .views import (
        BlogListView,
        BlogDetailView,
        BlogCreateView,
        BlogUpdateView,
        BlogDeleteView,
    )
    
    urlpatterns = [
        path('post/new/', BlogCreateView.as_view(), name='post_new'),
        path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
        path('post/<int:pk>/edit/',BlogUpdateView.as_view(), name='post_edit'),
        path('post/<int:pk>/delete/',BlogDeleteView.as_view(), name='post_delete'),
        path('', BlogListView.as_view(), name='home'),
    
    ]

base.html


    {% load static %}
    <html>
      <head>
        <title>Django blog</title>
        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
        rel="stylesheet">
        <link href="{% static 'css/base.css' %}" rel="stylesheet">
      </head>
      <body>
        <div>
          <header>
            <div class="nav-left">
              <h1><a href="{% url 'home' %}">Django blog</a></h1>
                <h2><a href="http://127.0.0.1:8000/admin/">Admin</a></h2>
    
            </div>
            <div class="nav-right">
               <a href="{% url 'post_new' %}">+ New Blog Post</a>
            </div>
          </header>
          {% if user.is_authenticated %}
            <p>Hi {{ user.username }}!</p>
          {% else %}
            <p>You are not logged in.</p>
            <a href="{% url 'login' %}">Log In</a><br>
              <p><a href="http://127.0.0.1:8000/accounts/signup/">Sign up</a></p>
          {% endif %}
        {% block content %}
        {% endblock content %}
        </div>
      </body>
    </html>
    
    
    
    <ul class="pagination">
        {% if page_obj.has_previous %}
            {% if page_obj.number|add:'-3' > 1 %}
                <li class="pagination__item">
                    <a href="?{{ post }}{{ post }}page=1">1</a>
                </li>
            {% endif %}
            {% if page_obj.number|add:'-3' >= 3 %}
                <li class="pagination__item pagination__item--dots">
                        <a href="?{{ genre }}{{ year }}page={{ page_obj.previous_page_number|add:'-3' }}">
                    <span class="pagination__link">• • •</span>
                    </a>
                </li>
            {% endif %}
        {% endif %}
        {% if paginator.page_range|length > 1 %}
            {% for i in paginator.page_range %}
                {% if page_obj.number == i %}
                    <li class="pagination__item active">
                        <a class="pagination__link" href="#">{{ i }}</a>
                    </li>
                {% elif i > page_obj.number|add:'-4' and i < page_obj.number|add:'4' %}
                    <li class="pagination__item">
                            <a class="pagination__link" href="?{{ genre }}{{ year }}page={{ i }}">{{ i }}</a>
                    </li>
                {% endif %}
            {% endfor %}
        {% endif %}
        {% if page_obj.has_next %}
            {% if page_obj.number|add:'4' < page_obj.paginator.num_pages %}
                <li class="pagination__item pagination__item--dots">
                        <a href="?{{ genre }}{{ year }}page={{ page_obj.next_page_number|add:'3' }}">
                    <span class="pagination__link">• • •</span>
                    </a>
                </li>
            {% endif %}
            {% if page_obj.number|add:'3' < page_obj.paginator.num_pages %}
                <li class="pagination__item">
                        <a class="pagination__link" href="?{{ genre }}{{ year }}page={{ page_obj.paginator.num_pages }}">
                            {{ page_obj.paginator.num_pages }}
                        </a>
                </li>
            {% endif %}
        {% endif %}
    </ul>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您的 post_detail.html 扩展了 base.html,因此您希望呈现的任何内容必须在某个块内,并且该块也必须出现在父模板(此处为 base.html)。您目前有一些内容在任何块之外,因此它们不会被渲染。将 HTML 放入块中,它会显示出来:

{% extends 'base.html' %}

{% block content %}
    <div class="post-entry">
        <h2>{{ post.title }}</h2>
        <p>{{ post.body }}</p>
    </div>

    <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p>
    <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p>
    <img src="{{ post.header_image.url|default_if_none:'fox.jpeg' }}">

    {{ post.body|urlize }}



    {% for comm in post.commentpost_set.all%}
        {{ comm.user }} <br>
        {{ comm.text }} <br><br>
    {% endfor %}


    <!-- put them inside the block -->


    <br><br>
    <hr>


    <form method="post">
        {% csrf_token %}
        {{ comment_form.as_p }}
        {% if request.user.is_authenticated %}
            <input type="submit" value="Submit" class="btn btn-outline-success">
        {% else %}
            <input type="submit" value="Submit" class="btn btn-outline-success" disabled>
        {% endif %}
    </form>
    
    <div class="main-comment-section">
        {{ comments.count }} Comment{{ comments|pluralize }}
        {% for comment in comments %}
            <blockquote class="blockquote">
                <p class="mb-0">{{ comment.content }}</p>
                <footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user|capfirst }}</cite></footer>
            </blockquote>
        {% endfor %}
    </div>
{% endblock content %}
相关问题