从Django添加评论

时间:2018-09-03 21:03:42

标签: python django comments

我正在尝试向我的topic.html页面添加一个表单,以便用户可以提交评论。当用户提交评论时,我想显示谁发表了评论以及时间和日期(见图片)

enter image description here

提交数据时,出现以下错误:

enter image description here

我认为这与以下事实有关:我没有指定要正确发布评论的用户,也没有传递用户要发布到的当前主题。

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required

from comments.models import Comment
from .models import Category, Entry, Topic
from .forms import CategoryForm, TopicForm, EntryForm, CommentForm


def topic(request, entry_id):
    """Show entry for single topic"""
    topic = Topic.objects.get(id=entry_id)
    entries = topic.entry_set.all()
    comments = Comment.objects.all()

    if request.method != 'POST':
        # No comment submitted
        form = CommentForm()
    else:
        # Comment posted
        form = CommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.user = request.user
            form.save()
            return HttpResponseRedirect(reverse('blogging_logs:topic'))

    context = {'topic': topic, 'entries': entries, 'comments': comments, 'form': form}
    return render(request, 'blogging_logs/topic.html', context)

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['content']
        labels = {'text': ''}
        widgets = {'text': forms.Textarea(attrs={'cols': 80})}

评论应用:model.py

from django.db import models
from django.conf import settings

from blogging_logs.models import Topic
# Create your models here.


class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    content = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.content)

1 个答案:

答案 0 :(得分:0)

您的Comment模型有一个Topic的外键,并且您没有指定允许为空。然后,您将拥有一个通过在“内容”字段中放置内容来创建Comment实例的表单。根据定义,这意味着您的主题字段为空或null,这是不允许的。只需以与添加用户类似的方式添加它,即

new_comment = form.save(commit=False)
new_comment.user = request.user
new_comment.topic = topic
form.save()