【问题标题】:not able to fetch comment from django templates无法从 django 模板中获取评论
【发布时间】:2019-02-05 07:44:04
【问题描述】:

我正在尝试在 django 中建立一个社交网络。在这段代码中,我试图通过模板中的模板框将 cmets 输入到帖子中。但是我的数据库中没有获取评论。我的代码如下:

我的 forms.py 为 cmets 创建了一个模型表单

forms.py

class CommentForm(forms.ModelForm):

class Meta:
    model = Comment
    fields = ('ctext',)

Models 有一个单独的评论模型,其中包含来自帖子模型和用户模型的外键。

models.py

class Post(models.Model):
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
imgfile = models.ImageField(upload_to='posts/', blank=True, null=True)

def publish(self):
    self.published_date=timezone.now()
    self.save()

def __str__(self):
    return self.title

class Comment(models.Model):
comment_auth = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.ForeignKey(Post, on_delete=models.CASCADE)
ctext = models.TextField(blank=True, null=True, max_length=200)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date=timezone.now()
    self.save()

def __str__(self):
    return self.ctext

我猜视图中的逻辑在调试时出现了错误

views.py

def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
post = get_object_or_404(Post, title=title)
cform = CommentForm()
comments = Comment.objects.all()
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()

    #cform = CommentForm(request.GET)
    #data = {}
    #Comment.ctext(**data)
    #if cform.is_valid():
    #comment={}
    #comment['ctext'] = request.POST['ctext']            
    #cform.changed_data['comment_auth'] = request.user
    #cform['comment_auth'] = request.user
    #cform['comment_auth_id_id'] = request.user

    #cform.save()

        return render(request, 'users/post_list.html', {'posts': posts, 'comments': comments, 'form': cform})
else:
    form = CommentForm()

return render(request, 'users/post_list.html', {'posts': posts, 'comments': comments, 'form': cform})

模板

 <div>
            <h2><a href="">{{ post.title }}</a></h2>
            <p>{{ post.text|linebreaksbr }}</p>
            {{image.imgfile.url}}
            {% if post.imgfile %}
                <img src="{{ post.imgfile.url }}" alt="{{ post.imgfile.url }}">
            {% endif %}
            <p>By:- {{ post.author }}</p>
            <p>published: {{ post.published_date }}</p>
            <form method="POST" class="post-form" action="/users/post/list">{% csrf_token %}
                {{ form }}
                {% for comment in post.comment_set.all %}
                    <p><b>Comments: </b></p>
                    <p><b>{{ comment.comment_auth }}: </b>{{ comment.ctext }}</p>
                {% endfor %}
                <button type="submit" class="save btn btn-default">Comment</button>
            </form>
        </div>

【问题讨论】:

  • title 定义在哪里?
  • 也将这个{% for comment in post.comment_set.all %}...{% endfor %}移到你的表单标签之外。
  • 可能正在使用使用“comment”的变量,它在模板标签中用于评论 {% comment %} {% encomment %}
  • @Ahtisham 你说的是哪个标题
  • 将此{% for comment in post.comment_set.all %} 更改为{% for comment in comments %},您能否使用Post 模型更新您的问题

标签: django django-models django-forms django-views


【解决方案1】:

我假设您已经通过 /admin 发布了帖子和评论条目,并且您能够获取您的帖子,根据您的问题,这里将是获取与帖子相关的 cmets 的最简单方法:

{% for post in posts %}
    <div>
      {{ post.title }}
      By - {{ post.author }}
      {% for comment in post.comment_set.all %}
<-- is now looking up for all comment entries, where this post is the set foreignkey -->
         <p><b>Comments: </b></p>
         <p><b>{{ comment.comment_auth }}: </b>{{ comment.ctext }}</p>
      {% endfor %}
    </div>
{% endfor %}

views.py:

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    context = {'posts': posts}
    return render(request, 'users/post_list.html', context)

django docs

【讨论】:

  • 您的数据库中是否还有一些 cmets?
  • 它将用于在页面上显示cmets。无法删除
  • 是的,我确实有 cmets,它们可以从 django 的管理端添加。
  • 不,你不知道。在模板中,您调用 cmets 槽 {% for comment in post.comment_set.all %} not 槽 {% for comment in cmets %}
  • 您能否编辑您的问题并添加您的帖子模型,或者检查您是否设置了相关名称?否则你可以试试 {% for comment in cmets %} {% if comment.title == post.title %} {% endif %} {% endfor %}
【解决方案2】:

修改views.py如下:

def post_list(request):

posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
comment_form = CommentForm()

comments = Comment.objects.all()
if request.method == "POST":
    data = {
        'ctext': request.POST['ctext'],
        'comment_auth_id': request.user.id,
        'title_id': request.POST['title_id']
    }
    comment_form = CommentForm(data=data)
    if comment_form.is_valid():            
        Comment.objects.create(**data)
    return render(request, 'users/post_list.html', {
        'posts': posts, 
        'comments': comments, 
        'form': comment_form
        })
else:

    return render(request, 'users/post_list.html', {
        'posts': posts, 
        'comments': comments, 
        'form': comment_form
    })

【讨论】:

    【解决方案3】:

    据我所知,您正在尝试发布新评论,而您的做法完全错误,这就是您无法显示 cmets 的原因。这是正确的做法:

    html:

    <p>{{ err_msg }}</p>
    {% for post in posts %}
        <div>
          <!-- Other elements -->          
          <form method="POST" action="/users/post/list">{% csrf_token %}
              {{ form }}   
              <!-- Sending id of post you are commenting on -->         
              <input type="hidden" name="post_id" value="{{post.id}}">
              <button type="submit">Comment</button>
          </form>
          <p><b>Comments: </b></p>
          {% for comment in post.comment_set.all %}             
             <p><b>{{ comment.comment_auth }}: </b>{{ comment.ctext }}</p>
          {% endfor %}
        </div>
    {% endfor %}
    

    views.py:

    def post_list(request):
       posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
       # I have removed the comments.objects.all 
       # as you getting them with post.comment_set.all in your template 
       form = CommentForm()
       data = {'posts': posts, 'form': form}    
       if request.method == "POST":
           # get the id of post you are commenting on
           cur_post_id = request.POST.get('post_id')
           try:
              # check if the post exists in the database.
              post = Post.objects.get(id=cur_post_id)
              comment_form = CommentForm(data=request.POST)
              if comment_form.is_valid():
                 new_comment = comment_form.save(commit=False)
                 new_comment.title= post
                 new_comment.comment_auth = request.user
                 new_comment.save()
           except:
              data['err_msg'] = 'Post does not exist!'  
       return render(request, 'users/post_list.html', data)     
    

    【讨论】:

    • @malavshah 我看不出我的回答有什么问题,但您仍然没有接受它,为什么?除了您如何发送title_id 您没有提及它之外,如果您评论的帖子不存在怎么办?您的解决方案肯定会失败。而我的不会。
    • @malavshah 如果您认为回答自己的问题然后接受它会在 stackoverflow 上获得积分,那么您完全错了。它不会为您带来任何收益,而如果您接受其他人的回答,它将为您带来 +2 分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2013-04-09
    • 2019-08-25
    • 1970-01-01
    相关资源
    最近更新 更多