添加评论表单 Django

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

http://img4.mukewang.com/60c07baa0001c50103560300.jpg

当我提交数据时,我收到以下错误:

http://img2.mukewang.com/60c07bb400019e3205510167.jpg

我相信这与我没有指定发布评论的用户有关。而且我没有传递用户发布的当前主题。


视图.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)

表格.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)


繁星点点滴滴
浏览 104回答 1
1回答

浮云间

您的 Comment 模型具有 Topic 的外键,并且您没有指定它允许为空。然后你有一个表单,它通过在“内容”字段中放置一些东西来创建 Comment 实例。根据定义,这意味着您的主题字段为空或 null,这是不允许的。只需像添加用户一样添加它,即new_comment = form.save(commit=False)new_comment.user = request.usernew_comment.topic = topicform.save()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python