Note that I am new in Django. I have been trying to give value for the 'post' instance of the form. What I want to do is link my comment to a specific post. I could link my comment to author with requesting a user that is currently logged in but cannot set the related post. I got two options for urls.py:
<int:pk>
which gives an error 'int' is not iterable
.<pk>
which gives an error Cannot resolve keyword '1' into field. Choices are: author, author_id, comments, content, date_posted, id, title
Cannot resolve keyword '1' into field. Choices are: author, author_id, comments, content, date_posted, id, title
## my views.py
class CommentCreateView(LoginRequiredMixin,CreateView):
model = Comment
fields = ['content']
def form_valid(self,form):
form.instance.author = self.request.user
form.instance.post = Post.objects.filter(self.kwargs['pk']).first()
return super().form_valid(form)
## my models.py
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.content
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
## my urls.py
path('post/<pk>/comment/', CommentCreateView.as_view(), name="comment-create")
您没有正确调用.filter()
,您需要传递关键字参数。
form.instance.post = Post.objects.get(pk=self.kwargs['pk'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.