I am using a Django CreateView and I wanted to set the success_url
to the same view so that when the form is posted, it displays the same page and I can display the created object in addition to the form in case you want to add a new one. However, self.object
is None because of this in BaseCreateView
:
def post(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).post(request, *args, **kwargs)
I am concluding that a CreateView is not made to be redisplayed after success?
I was looking at the wrong place.
I have to override form_valid
to not redirect to the URL (return HttpResponseRedirect(self.get_success_url())
)
def form_valid(self, form):
self.object = form.save()
# Does not redirect if valid
#return HttpResponseRedirect(self.get_success_url())
# Render the template
# get_context_data populates object in the context
# or you also get it with the name you want if you define context_object_name in the class
return self.render_to_response(self.get_context_data(form=form))
I don't think you need the object being created to redirect to the same URL of the view. I'd use reverse:
class MyModelCreate(CreateView):
model = MyModel
success_url = reverse('path.to.your.create.view')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With