但我已经提到了主键,不是吗?
它说这个错误与:
有关class CommentUpdate(UpdateView):
model = Comment
fields = ['body']
def form_valid(self, form):
film = Film.objects.get(pk=self.kwargs['film_id'])
comment = Film.objects.get(pk=self.kwargs['comment_id'])
form.instance.user = self.request.user
form.instance.film = film
form.instance.comment = comment
return super(CommentUpdate, self).form_valid(form)
如果上面的代码能够正常工作但我必须创建评论的视图可以解决此问题,我不确定这个问题是否已解决:
class CommentCreate(CreateView):
model = Comment
fields = ['body']
def form_valid(self, form):
film = Film.objects.get(pk=self.kwargs['film_id'])
form.instance.user = self.request.user
form.instance.film = film
return super(CommentCreate, self).form_valid(form)
我的urls.py:
path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'),
path('<int:film_id>/comment/<int:comment_id>/', views.CommentUpdate.as_view(), name='update_comment'),
模型:
class Comment(models.Model):
# user = models.ForeignKey(User, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
film = models.ForeignKey(Film, on_delete=models.CASCADE)
body = models.CharField(max_length=200)
def get_absolute_url(self):
return reverse('films:detail', kwargs={'pk': self.film.pk})
我有html链接:
<a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a>
<a href="{% url 'films:update_comment' film_id=film.id comment_id=comment.id %}">Update</a>
答案 0 :(得分:1)
UpdateView调用get_object
方法,该方法需要pk
或slug
url参数才能获取更新对象。您可以使用pk_url_kwarg
更改参数名称:
class CommentUpdate(UpdateView):
model = Comment
fields = ['body']
pk_url_kwarg = 'comment_id'