[Solved]-Django createview with success_url being the same view?

15πŸ‘

βœ…

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))
πŸ‘€Michael

3πŸ‘

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')
πŸ‘€dukebody

1πŸ‘

So it’s 6 years later and I bumped into this problem while working on my project. In case anyone also faces this problem too in the near future here is a simple and easy fix but might not be recommended but it got the job done for me.

By the way I like using ClassBasedViews.

In your views.py file

class MyMode(CreateView):
    model = my_model
    success_url = '/path-to-webpage/'
     

So what I basically did was to hard-code in the path to the web-page under the success_url and that got the problem solved.
This works when you are not planning to change your URLpatterns anytime otherwise you will also have to change the URL in the views.py file too.

πŸ‘€Surveyor Jr

Leave a comment