python - 如何在 django 上添加评论
问题描述
我正在尝试向我的项目添加评论系统,所有代码看起来都很好,但我收到此错误“ValueError at / The QuerySet value for an exact lookup must be limited to one result using slicing”。我不知道出了什么问题,但错误可能在 views.py 文件上。
视图.py
def imagelist(request):
images = Post.objects.all()
post = get_object_or_404(Post)
comments = Comment.objects.filter(post=images)
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
contentt = request.POST.get('content')
comment = Comment.objects.create(post=images, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context2 = {
"images": images,
"comments": comments,
"comment_form": comment_form,
}
return render(request, 'imagelist.html', context2)
模型.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
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))
class Post(models.Model):
text = models.CharField(max_length=200)
posti = models.ImageField(upload_to='media/images', null=True, blank="True")
video = models.FileField(upload_to='media/images', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
updated = models.DateTimeField(auto_now=True)
created =models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.tittle)
表格.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
解决方案
您需要将create
单个注释传递给注释的方法,Post
因为相应的字段是 aForeignKey
并且您正在传递整个查询集 ( Post.objects.all()
)
您只需要获得评论应该存在的帖子。
single_post = Post.objects.get(pk=the_post_pk)
comment = Comment.objects.create(post=single_post, user=request.user, content=content)
推荐阅读
- snowflake-cloud-data-platform - 'COPY INTO' sql 查询的 files_pattern 使用什么正则表达式解析器?
- android - 我现在可以使用 Firebase 吗?
- java - Spring Boot Chaos Monkey 不使用 feign
- rxjs - 在 RxJs 中进行一些操作后,有没有办法将子属性合并回父源?
- multithreading - Perl:从并行线程派生
- flutter - Flutter:如何从 Dismissible onDismissed 访问上下文
- docker - 如何在同一个 docker 容器或测功机中运行 2 个进程?
- c# - 基于底层健康检查的健康检查状态
- javascript - ES6 生成器代码中任务/执行的用户是什么?
- sql - 按小时显示“打开”记录数的数据透视表