如何在django上添加评论

2ekbmq32  于 2023-01-31  发布在  Go
关注(0)|答案(4)|浏览(142)

我试图添加一个注解系统到我的项目,所有的代码看起来很好,但我得到这个错误“ValueError at /的QuerySet值为一个确切的查找必须限制为一个结果使用切片”。我不知道是什么错误,但错误可能是在views.py文件。
views.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)

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

forms.py

class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ('content',)
beq87vna

beq87vna1#

您需要向注解的create方法传递单个Post,因为对应的字段是ForeignKey,并且您传递的是整个查询集(Post.objects.all()
你需要得到的只是评论应该生活的职位。

single_post = Post.objects.get(pk=the_post_pk)
comment = Comment.objects.create(post=single_post, user=request.user, content=content)
5cnsuln7

5cnsuln72#

问题是你这样写:

images = Post.objects.all()
comments = Comment.objects.filter(post= images)

这里images是一组Post对象,而不是单个Post对象,因此你不能过滤它,但是你实际上 * 不 * 需要这样做。
此外,在您的Comment模型的__str__中还有一个小错误:

class Comment(models.Model):
    # …

    def __str__(self):
        return '{}-{}'.format(self.post.text, self.user.username)

但是视图本身看起来很奇怪,因为你在这里写了一个Post的列表,但是如果你发出POST请求,你需要知道你想把Comment提交给哪个帖子,因此至少接受POST请求的视图需要知道要评论的Post的主键。例如,你可以在urls.py中编码:

# appname/urls.py

from django.urls import path
from app import views

urlpatterns = [
    path('post/<int:pk>/', views.post_detail, name='post_detail'),
    path('post/', views.post_list, name='post_detail')
]

在该视图中,我们可以获取条目,例如使用get_object_or_404,并且在POST的情况下设置视图中的postuser对象:

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

@login_required
def post_detail(request, pk):
    image = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
          comment_form = CommentForm(request.POST, request.FILES)
          if comment_form.is_valid():
            comment_form.instance.user = request.user
            comment_form.instance.post = image
            comment_form.save()
            return redirect(post)
    else:
        comment_form = CommentForm()
    context = {
        'post': image,
        'comment_form': comment_form,
    }
    return render(request, 'imagedetail.html', context)

在您的模板中,您可以使用以下内容呈现帖子的评论:

{{ post }}
{% for comment in post.comment_set.all %}
    {{ comment }}
{% endfor %}
<form method="post" action="{% url 'post_detail' pk=post.pk %}">
    {% csrf_token %}
    {{ comment_form }}
</form>

你也可以创建一个呈现列表的视图:

@login_required
def post_list(request, pk):
    images = Post.objects.prefetch_related('comment_set')
    comment_form = CommentForm()
    context = {
        'image': images,
        'comment_form': comment_form,
    }
    return render(request, 'imagelist.html', context)

在列表的模板中,可以使用以下命令渲染列表:

{% for post in images %}
    {{ post }}
    {% for comment in post.comment_set.all %}
        {{ comment }}
    {% endfor %}
    <form method="post" action="{% url 'post-detail' pk=post.pk %}">
        {% csrf_token %}
        {{ comment_form }}
    </form>
{% endfor %}

因此,我们在这里向post-detail视图发出POST请求。

iaqfqrcu

iaqfqrcu3#

经过4个小时的搜索,这就是我实现它的方法。我所做的就是添加这个新的视图,方法,url和html。希望这能有所帮助!
views.py

def imagedetail(request, pk):
       post = get_object_or_404(Post, pk=pk)
       comments = Comment.objects.filter(post=post)
       if request.method == 'POST':
         comment_form = CommentForm(request.POST or None)
         if comment_form.is_valid():
           content = request.POST.get('content')
           comment = Comment.objects.create(post=post, user=request.user, content=content)
           comment.save()
           return HttpResponseRedirect(post.get_absolute_url())

       else:
         comment_form = CommentForm()
       context2 = {
          "comments": comments,
          "comment_form": comment_form,
       }
       return render(request, 'imagedetail.html', context2)

models.py (on模型)

def get_absolute_url(self):
        return reverse('imagedetail', args=[self.id])

urls.py (for 新视图,即图像详细信息)

path('imagedetail/<int:pk>/', views.imagedetail, name='imagedetail'),

imagelist.html(重定向到imagedetail,顺便说一句,这是一个引导按钮)

<a role="button" class="btn btn-primary" href="{% url 'imagedetail' pk=image.pk %}"></a>

imagedetail.html(它只显示评论)

<form method="post">
      {% csrf_token %}
      {{comment_form.as_p}}
      {% if request.user.is_authenticated %}
        <input type="submit" value="Submit" class="btn btn-outline-succes">
      {% else %}
        <input type="submit" value="Submit" class="btn btn-outline-succes" disabled>
      {% endif %}
    </form>
    <div class="main-comment-section">
      {{ comments.count }}
      {% for comment in comments %}
        <blockquote class="blockquote">
            <p class="mb-0">{{ comment.content }}</p>
            <footer class="blockquote-footer">by <cite title="Source Title">{{ comment.user }}</cite></footer>
        </blockquote>
      {% endfor %}
    </div>
ruarlubt

ruarlubt4#

2 -forms.py我爱你:

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

# overriding default form setting and adding bootstrap class
def __init__(self, *args, **kwargs):
    super(CommentForm, self).__init__(*args, **kwargs)
    self.fields['name'].widget.attrs = {'placeholder': 'Enter name', 'class': 'form-control'}
    self.fields['body'].widget.attrs = {'placeholder': 'Comment here...', 'class': 'form-control', 'rows': '5'}

3 -models.py电子邮件:

class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
name = models.CharField(max_length=50)
parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
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 self.name

def get_comments(self):
    return Comment.objects.filter(parent=self).filter(active=True)

4 -views.py发表于贝雷·戈伦梅利迪:

def post (request,slug):
post = Post.objects.get(slug = slug)
latest = Post.objects.order_by('-timestamp')[:3]
comments = post.comments.filter(active=True)
new_comment = None
comment_form = CommentForm()

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()
    comment_form = CommentForm()

context = {
    'post': post,
    'latest': latest,
    'comments': comments,
    'comment_form': comment_form
}
return render(request, 'post.html', context)

5 - post.html作者阿尔蒂纳分隔器登sonra elave埃莱:

<hr/>
    <h3>Add Comment</h3>
    <form method="post" action="">
        {% csrf_token %}
        {{ comment_form.as_p }}
        <button type="submit" class="btn btn-primary">Comment</button>
    </form>

    {% with comments.count as total_comments %}
        <h3 class="mt-5">
            {{ total_comments }} comment{{ total_comments|pluralize }}
        </h3>
    {% endwith %}
    {% if not post.comments.all %}
        No comments yet

    {% else %}
        {% for comment in post.get_comments %}
            {% include 'comment.html' with comment=comment %}
        {% endfor %}
    {% endif %}
</div>

6 -admin.py电子邮件:

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display=('name', 'post', 'created', 'active')
list_filter = ('active', 'created', 'updated')
search_fields = ('name', 'body')

7 -评论模板. html您的评论和图片等:

<div class="border-0 border-start border-2 ps-2" id="{{comment.id}}">

    <div class="mt-3">
        <strong>{{comment.name}}</strong>
        {% if  comment.parent.name%} to <strong>{{comment.parent.name}}</strong>{% endif %}
        <small class="text-muted">On {{ comment.created.date }}</small>
    </div>
    <div class="border p-2 rounded">
        <p>{{comment.body}}</p>
        <button class="btn btn-primary btn-sm" onclick="handleReply({{comment.id}})">Reply</button>

        <div id="reply-form-container-{{comment.id}}" style="display:none">

           
        </div>
    </div>
    {% for comment in comment.get_comments %}
        {% include 'comment.html' with comment=comment %}
    {% endfor %}

8 -模型德邮政联合国阿尔蒂纳elave埃莱

def get_comments(self):
    return self.comments.filter(parent=None).filter(active=True)

相关问题