Python Django在用户自动成为作者的帖子上发表用户评论

Python Django在用户自动成为作者的帖子上发表用户评论,python,django,Python,Django,你好,我正在尝试制作一个django应用程序,当发布一篇帖子时,登录的人可以对帖子发表评论,但它会自动插入他们的姓名/帐户,而不是他们必须把它放进去。因此,用户所要做的就是添加正文内容。 forms.py ''' ''' views.py ''' ''' models.py ''' ''' url.py ''' 现在,我的项目中的代码如下所示 “”“ “”“ 当有人添加注释时,它基本上会刷新页面并按预期显示新注释您可以将其修补到对象,就像您对所做的那样。post: from django.con

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

''' views.py '''

''' models.py '''

''' url.py '''

现在,我的项目中的代码如下所示 “”“

“”“
当有人添加注释时,它基本上会刷新页面并按预期显示新注释

您可以将其修补到对象,就像您对
所做的那样。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})
从django.contrib.auth.decorators导入登录名\u必需
从django.shortcuts导入重定向
@需要登录
def post_详细信息(请求、年、月、日、职务):
post=获取对象或404(post,slug=post,状态='cleared',发布年=年,发布月=月,发布日=日)
comments=post.comments.filter(active=True)
如果request.method==“POST”:
评论形式=评论形式(数据=request.POST)
如果注释形式有效():
comment_form.instance.post=post
comment_form.instance.name=request.user
新建注释表单。保存()
返回重定向('name-of-some-view')
其他:
注释形式=注释形式()
返回呈现(请求,'posts/post/detail.html',{'post':post,'comments':comments,'comments\u form':comments\u form})

注意:您可以将视图限制为具有


注意:通常最好使用来引用用户模型,而不是直接使用。有关更多信息,请参见


注意:如果POST请求成功,您应该 实施。 这样可以避免在用户刷新日志时发出相同的POST请求 浏览器


我按照你的指示做了,但我仍然得到:“没有这样的专栏:posts\u comment.name\u id”作为一个错误,当我尝试加载页面时,我在另一个应用程序idk中使用了用户模型,如果这是导致错误的原因it@JoeG:啊,看起来你也忘记迁移数据库了(
makemigrations
migrate
)。我进行了迁移,但似乎我必须删除所有以前的迁移和数据库,而且它似乎确实可以工作,但是现在当我尝试发布时,我收到一个错误消息(“新的注释表单”未定义)顺便说一句,非常感谢你的帮助,我已经在这上面呆了好几个小时了。当我把上一个(新的评论表单)改为评论表单。保存()JoeG:啊,但是
'name-of-some-view'
应该被替换为它应该重定向到的视图的名称。如果帖子成功,你应该重定向:好的,我明白你的意思了,谢谢你的耐心和帮助,我将继续尝试正确的重定向URL
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})
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}'
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'),
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})
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})