我正在尝试向我的topics.html 页面添加一个表单,以便用户可以提交评论。当用户提交评论时,我想显示发表评论的人以及时间和日期(见图)
当我提交数据时,我收到以下错误:
我相信这与我没有指定发布评论的用户有关。而且我没有传递用户发布的当前主题。
视图.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)
浮云间
相关分类