Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django createview with success_url being the same view?

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?

like image 784
Michael Avatar asked Oct 25 '14 15:10

Michael


2 Answers

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))
like image 196
Michael Avatar answered Sep 22 '22 16:09

Michael


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')
like image 20
dukebody Avatar answered Sep 21 '22 16:09

dukebody