I want to show comments unique to the blog post on each blog post but when I click submit on the comment posting form it throws an error saying
IntegrityError at /post/6/comment/ NOT NULL constraint failed: blog_postcomment.Post_id
I add comments in the database manually but it doesn't show on my page.
HTML
{% block content %}<div class="container"><div class="row"><div class="col-md-8 card mb-4 mt-3 left top"><div class="card-body">
{% if comment_list %}<h2 class="post-title">Comments</h2>
{% for comment in blog_postcomment.post %}<p class=" text-muted">{{ comment.author }} | {{ comment.post_date }}</p><p class="card-text ">{{ comment.description | safe }}</p>
{% endfor %}
{% endif %}</div></div></div></div>
{% block content %}
model
class PostAuthor(models.Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
bio = models.TextField(max_length=400, help_text="Enter your bio details here.")
class Meta:
ordering = ["user", "bio"]
def get_absolute_url(self):
return reverse('post-by-author', args=[str(self.id)])
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=200, unique=False)
slug = models.SlugField(max_length=200, null=True, blank=True)
author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def get_absolute_url(self):
return reverse('post-detail', args=[str(self.id)])
def __str__(self):
return self.title
class PostComment(models.Model):
description = models.TextField(max_length=1000, help_text="Enter your comment here.")
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
post_date = models.DateTimeField(auto_now_add=True)
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
class Meta:
ordering = ["post_date"]
def __str__(self):
len_title = 75
if len(self.description) > len_title:
titlestring = self.description[:len_title] + '...'
else:
titlestring = self.description
return titlestring
View
class PostListbyAuthorView(generic.ListView):
model = Post
template_name = 'blog/post_list_by_author.html'
def get_queryset(self):
id = self.kwargs['pk']
target_author = get_object_or_404(PostAuthor, pk=id)
return Post.objects.filter(author=target_author)
def get_context_data(self, **kwargs):
context = super(PostListbyAuthorView, self).get_context_data(**kwargs)
context['post'] = get_object_or_404(PostAuthor, pk=self.kwargs['pk'])
return context
class IndexPage(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/all_posts.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
class PostCreate(CreateView):
model = Post
fields = '__all__'
template_name = 'blog/post_form.html'
class PostUpdate(UpdateView):
model = Post
fields = ['content', 'title']
template_name = 'blog/edit_post.html'
class PostComment(LoginRequiredMixin, CreateView):
model = PostComment
fields = ['description', ]
template_name = 'blog/comment_form.html'
def get_context_data(self, **kwargs):
context = super(PostComment, self).get_context_data(**kwargs)
context['post'] = get_object_or_404(Post, pk=self.kwargs['pk'])
return context
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.post = get_object_or_404(Post, pk=self.kwargs['pk'])
return super(PostComment, self).form_valid(form)
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.kwargs['pk'], })
urlpatterns = [
path('', views.IndexPage.as_view(), name='index'),
path('posts/', views.PostList.as_view(), name='all-posts'),
path('post/detail/<int:pk>', views.PostListbyAuthorView.as_view(), name='post-by-author'),
path('post/author/<int:pk>', views.PostDetail.as_view(), name='post-detail'),
path('post/create/', views.PostCreate.as_view(), name='post-create'),
path('post/<int:pk>/edit/', views.PostUpdate.as_view(), name='post-edit'),
path('post/<int:pk>/comment/', views.PostComment.as_view(), name='post-comment'),
path('accounts/', include('django.contrib.auth.urls')),
]