我正在尝试向我的topics.html 页面添加一个表单,以便用户可以提交评论。当用户提交评论时,我想显示发表评论的人以及时间和日期(见图)当我提交数据时,我收到以下错误:我相信这与我没有指定发布评论的用户有关。而且我没有传递用户发布的当前主题。视图.pyfrom django.shortcuts import renderfrom django.http import HttpResponseRedirect, Http404from django.urls import reversefrom django.contrib.auth.decorators import login_requiredfrom comments.models import Commentfrom .models import Category, Entry, Topicfrom .forms import CategoryForm, TopicForm, EntryForm, CommentFormdef 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)表格.pyclass CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80})}评论应用程序:model.pyfrom django.db import modelsfrom django.conf import settingsfrom 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 回答
浮云间
TA贡献1829条经验 获得超4个赞
您的 Comment 模型具有 Topic 的外键,并且您没有指定它允许为空。然后你有一个表单,它通过在“内容”字段中放置一些东西来创建 Comment 实例。根据定义,这意味着您的主题字段为空或 null,这是不允许的。只需像添加用户一样添加它,即
new_comment = form.save(commit=False)
new_comment.user = request.user
new_comment.topic = topic
form.save()
添加回答
举报
0/150
提交
取消