当一个页面上显示多个帖子时,我想链接一个评论模型来发布。我想访问我正在评论的帖子的帖子id,但我不知道如何链接评论模型我是这里的初学者,所以我为任何错误道歉请评论是否需要更多的代码
模板:
{% for Img in imgs %}
<div class="container">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="{{ Img.Post_Img.url }}" alt="image">
</div>
<div class="card-content">
<img src="{{ Img.op.userprofile.Profile_pic.url }}" class="profiles" alt="{{ Img.op.userprofile.Nick_Name }}">
<span class="OP">{{ Img.op.userprofile.Nick_Name }}</span>
<span class="card-title activator white-text text">{{ Img.Title }}<i class="material-icons right">more_vert</i></span>
<p><a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Vote</a></p>
</div>
<div class="card-reveal darken-4 black">
<span class="card-title white-text text">{{ Img.Title }}<i class="material-icons right">close</i></span>
<form method="post">
{% csrf_token %}
{{ comment }}
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
{% for comment in comments %}
{{ comment.op.userprofile.Nick_Name }}{{ comment.comment }}
{% endfor %}
</div>
</div>
</div>
{% endfor %}
型号:
class MemeImg(models.Model):
Title = models.CharField(max_length=500)
date_created = models.DateTimeField(auto_now_add=True)
op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
Post_Img = CloudinaryField('Post')
def __str__(self):
return self.Title
class Comments(models.Model):
post = models.ForeignKey(MemeImg, on_delete=models.CASCADE)
op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1)
comment = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.post.Title
视图(不起作用,抛出错误而非空约束(:
def user_home(request):
func = data(request)
url = func[0]
name = func[1]
comment = CommentSection(request.POST)
if request.method == 'POST':
comment = CommentSection(request.POST)
if comment.is_valid():
comment.save(commit=False)
comment.op = request.user
comment.save()
comments = Comments.objects.all()
imgs = MemeImg.objects.all()
ctx = {
'imgs': imgs,
'url': url,
'name': name,
'comment': comment,
'comments': comments,
}
return render(request, 'User_Home.html', ctx)
您需要为Comments
模型中的ForeignKey指定null=True
和blank=True
,或者在makemigrations
时必须在中设置默认值。
默认情况下,字段不允许使用None
值,除非您明确允许,因为默认情况下Comments
模型的post
属性设置为null=False
。
当您在comment.post = None
中创建一个注释和其他内容时,Django会尝试找到一个默认值。但是您也没有指定默认值,所以Django会引发错误,因为它找不到任何可以填充的字段
因此,Comments
模型的后字段应该看起来像:
post = models.ForeignKey(MemeImg, on_delete=models.CASCADE, null=True, blank=True)