Комментарии не загружаются в Django - PullRequest
0 голосов
/ 27 января 2020

Я провел много экспериментов и очень чувствую себя вне своей глубины. Я не могу отобразить существующие комментарии (я добавил их через страницу администратора) или форму комментария. Я попытался Google решить проблему и изменить свой код. К сожалению, я не имею ни малейшего представления, что является причиной проблемы. Так что я не знаю, проводил ли какой-либо из моих экспериментов удаленно правильные линии.

После публикации исходного вопроса я попытался использовать dispatch () в своем коде. Я получил сообщения об ошибках, которые я пытался отправить в Google, но я просто пытался применить помощь группы поверх помощи группы.

enter image description here

enter image description here

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 %}

views.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')

forms.py

from .models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

models.py

  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)

urls.py (в приложении «Блог»)

from django.urls import path
from .views import (
    PostListView,
    PostDetailView,
    PostCreateView,
    PostUpdateView,
    PostDeleteView
)
from. import views
from django.views.generic import TemplateView

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('about/', views.about, name='blog-about'),
    path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook")
]

signal.py (в приложении «Пользователи»)

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver 
from .models import Profile

@reciever(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created: 
        Profile.objects.create(user=instance)

@reciever(post_save, sender=User)
def save_profile(sender, instance, created, **kwargs):
    instance.profile.save()

1 Ответ

2 голосов
/ 27 января 2020

исправьте свой отступ кода

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})
...