首页 > 解决方案 > Django对用户自动成为作者的帖子进行用户评论

问题描述

您好,我正在尝试制作一个 django 应用程序,当发布帖子时,登录的人可以对帖子发表评论,但它会自动插入他们的姓名/帐户,而不是他们必须输入。所以用户所要做的就是添加正文内容。forms.py '''

from django import forms
from .models import Comment

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

'''views.py '''

from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import CommentForm
from django.contrib.auth.models import User



class PostListView(ListView):
    queryset = Post.cleared.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'posts/post/list.html'



def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
    comments = post.comments.filter(active=True)
    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,'posts/post/detail.html', {'post':post , 'comments': comments,'new_comment': new_comment,'comment_form': comment_form})

''' 模型.py '''

from django_currentuser.db.models import CurrentUserField
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.conf import settings

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                    self).get_queryset()\
                         .filter(status='cleared')
class Post(models.Model):
    STATUS_CHOICES = (
        ('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),)
    title = models.CharField(max_length = 300)
    slug = models.SlugField(max_length = 300, unique_for_date='publish')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True)
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared')
    objects = models.Manager()
    cleared = PublishedManager()
    class Meta:
        ordering =('-publish',)
    def __str__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
    
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.SET_NULL, related_name='comments',null=True)
    name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)
    class Meta:
        ordering = ('created',)
    def __str__(self):
        return f'Comment by {self.name} on {self.post}'

''' urls.py '''

from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views
app_name = 'posts'
urlpatterns = [
    #path('', views.post_list, name='post_list'),
    path('', views.PostListView.as_view(), name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),

''' 使用当前代码,当我转到 post_detail 页面时出现此错误“没有这样的列:posts_comment.name_id”

编辑 万一有人在重定向时遇到问题我发现了一些有效的代码

from django.http import HttpResponseRedirect
from mysite.blog.models import Post

def comment_posted( request ):
    if request.GET['c']:
        comment_id, post_id  = request.GET['c'].split( ':' )
        post = Post.objects.get( pk=post_id )

        if post:
            return HttpResponseRedirect( post.get_absolute_url() )

    return HttpResponseRedirect( "/" )

现在代码在我的项目“””上看起来像这样

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
    comments = post.comments.filter(active=True)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            comment_form.instance.post = post
            comment_form.instance.name = request.user
            comment_form.save()
            return HttpResponseRedirect( post.get_absolute_url() )
    else:
        comment_form = CommentForm()
    return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form})

""" 当有人添加评论时,它基本上会刷新页面并按预期显示新评论

标签: pythondjango

解决方案


您可以将其修补到对象上,就像您对.post:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
    comments = post.comments.filter(active=True)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            comment_form.instance.post = post
            comment_form.instance.name = request.user
            new_comment_form.save()
            return redirect('name-of-some-view')
    else:
        comment_form = CommentForm()
    return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form})

注意:您可以使用@login_required装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图 。


注意:通常使用settings.AUTH_USER_MODEL[Django-doc]引用用户模型比直接使用User模型 [Django-doc]更好。有关更多信息,您可以查看文档的引用User模型部分


注意:如果 POST 请求成功,您应该制作一个redirect [Django-doc] 来实现Post/Redirect/Get模式 [wiki]。这样可以避免在用户刷新浏览器时发出相同的 POST 请求。


推荐阅读