我希望能够通过点击帖子下的评论链接来创建评论,每个帖子都有一个主题,但我无法获得特定帖子下的评论,所以我想添加主题以及更多功能,但我发现很难根据我评论的帖子自动分配主题
我的views.py pk 设置为post.id
def comment(request, pk):
form = commentform()
context = {
'form' : form
}
if request.method == 'POST':
form = commentform(request.POST)
if form.is_valid():
forms = form.save(commit=False)
forms.posts = post.objects.get(id=pk)
forms.owner = request.user
forms.topics = topic.objects.get(id=pk)
forms.save()
return redirect('home')
return render(request, 'base/comment.html', context)
我的模型.py
class comments(models.Model):
topics = models.ForeignKey(topic, on_delete=models.CASCADE, SET_NULL=True, null=True)
created = models.DateTimeField(auto_now=True)
posts = models.ForeignKey(post, on_delete=models.CASCADE)
owner = models.ForeignKey(User, on_delete=CASCADE)
comment = models.TextField(max_length= 500)
def __str__(self):
return str(self.comment)
class post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
Topic = models.ForeignKey(topic, on_delete=models.CASCADE)
post = models.TextField(max_length=500)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return f'{self.post}'
我的表格.py
class commentform(ModelForm):
class Meta:
model = comments
fields = ['comment']