hi everyone i got this error when i post a comment although the comment is posting but it give me this error and do not go to any redirect URL my views.py file is:
class CommentCreateView(CreateView): model = Comment form_class = CommentForm template_name = 'add-comment.html' # fields = '__all__' def form_valid(self, form): form.instance.product = Product.objects.get(slug=self.kwargs['slug']) return super().form_valid(form) success_url = reverse_lazy('products:detail')
my urls.py is:
urlpatterns = [ path('', ProductListView.as_view(), name= "list"), path('new/', ProductCreateView.as_view(), name="product-create"), path('<slug:slug>/update/', ProductUpdateView.as_view(), name="product-update"), path('<slug:slug>/delete/', ProductDeleteView.as_view(), name="product-delete"), path('<slug:slug>/comment', CommentCreateView.as_view(), name="add-comment"), path('<slug:slug>', ProductDetailSlugView.as_view(), name="detail"), ]
my models.py file is:
class Comment(models.Model): product=models.ForeignKey(Product, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) # def get_absolute_url(self): # return reverse("products:detail", kwargs={"slug": self.slug}) def __str__(self): return '%s - %s'%(self.product.title, self.name)
and my add-comment.html is:
{% extends "base.html"%} {% load crispy_forms_tags%} {% block content %} <h2 class="text-center">comment here...</h2> <div class="col-md-6 offset-md-3"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{form|crispy}} </fieldset> <button class="btn btn-secondary" >Add comment</button> </form>
and when i click on add comment it is adding comment but do not redirect to that page. the error is: enter image description here
You're trying to redirect to success_url = reverse_lazy('products:detail')
but without any argument (eg a slug).
You should rather use:
class CommentCreateView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add-comment.html'
def form_valid(self, form):
form.instance.product = Product.objects.get(slug=self.kwargs['slug'])
return super().form_valid(form)
def get_success_url(self):
return reverse('detail', kwargs={'slug' : self.object.slug})
Here, you get the url through get_success_url
and you can pass in the slug of the created instance.
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.