Success_url from created object url in FormView

I have a form class view which creates an object (a product in a catalog) when the user fills the form. The object is created inside the form_valid method of the view. I want that the view redirects to the created object url (the product url) through the "success_url" atribute of the FormView.

The problem is that I do not know how to specify that url in the success_url method, since the object is still not created when the class itself is defined. I have tried with reverse_lazy, or the get_absolute_url() method of the object, but the same problem persists.

class ImageUpload(FormView):
 [...]
 success_url = reverse_lazy('images:product', kwargs={'id': product.id })
 [...]
 def form_valid(self, form):
  [...]
  self.product = Product.objects.create(
        user=self.request.user, title=title)

Upvotes: 2

Views: 1903

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

Well at the class-level, there is no product, so you can not use product in the success_url.

What you can do is override the get_success_url, and thus determine the URL, like:

from django.urls import reverse

class ImageUpload(FormView):

    def get_success_url(self):
        return reverse('images:product', kwargs={'id': self.product.id })

    def form_valid(self, form):
        self.product = Product.objects.create(user=self.request.user, title=title)
        return super(ImageUpload, self).form_valid(form)

In fact by default the get_success_url fetches the success_url attribute, and resolves it.

Upvotes: 6

Related Questions