Reputation: 61
I want to redirect to my post-detail page after entering the comment. In my code it redirects not to Post's pk, but to Comment's pk. Therefore the path brings me to an incorrect place and the page does not exist.
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})
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.get(pk=self.kwargs['pk'])
return super().form_valid(form)
urls.py
path('post/new/', PostCreateView.as_view(), name="post-create"),
path('post/<int:pk>/', views.post_detail, name="post-detail"),
...
Upvotes: 0
Views: 56
Reputation: 506
Django Generic views will automatically take the pk of the model the view is assigned, in this case, Comment
. If you want to change the URL it redirects to you can override get_success_url
in CommentCreateView
.
eg,
class CommentCreateView(LoginRequiredMixin,CreateView):
model = Comment
fields = ['content']
def get_success_url(self):
return reverse('post-detail', kwargs={'pk':self.object.post.pk})
Upvotes: 1