python - 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})
""" 当有人添加评论时,它基本上会刷新页面并按预期显示新评论
解决方案
您可以将其修补到对象上,就像您对.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 请求。
推荐阅读
- python - 如何将新行加入python数据框中的现有行
- jquery - 通过 jQuery 的 Ajax 请求与普通调用
- c# - 减去两个 ViewBag 值
- wordpress - 预加载 WooCommerce star.woff 字体
- automation - 什么是最实用的自动化和任务调度工具,为什么?
- spring-boot - COPY target/test-0.0.1-SNAPSHOT.jar /test.jar COPY failed 找不到文件 Docker
- c# - 导入非托管 DLL 的 C# 多线程
- android - 如何使用 Kivy 在 python 中的 Android 应用程序上使用可点击按钮?
- ios - Apple Core ML 无法使用混合的 swift 和 Objective-C 进行编译
- mql5 - mql5 : OnCalculate 每根柱线指标的收盘价差