无法从Django模板获取评论

时间:2019-02-05 07:44:05

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

我正在尝试在Django中建立一个社交网络。在这段代码中,我试图通过模板中的模板框输入对帖子的评论。但是注释未在我的数据库中获取。我的代码如下:

我的forms.py为评论创建模型表单

forms.py

class CommentForm(forms.ModelForm):

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

模型具有单独的注释模型,该模型具有来自帖子模型和用户模型的外键。

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>

3 个答案:

答案 0 :(得分:1)

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

{% 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

答案 1 :(得分:0)

据我了解,您正在尝试发布新评论,而您的操作方式完全错误,这就是您无法显示评论的原因。这是正确的方法:

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)     

答案 2 :(得分:0)

更改 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
    })