Django createview with success_url being the same view?

I use Django CreateView, and I wanted to set success_url in the same way so that when the form is submitted, the same page is displayed, 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 conclude that CreateView will not be re-displayed after success?

+5
source share
2 answers

I was looking for the wrong place.

I need to override form_valid so as not to redirect 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)) 
+4
source

I don’t think you need the created object to redirect to the same view URL. I would use reverse :

 class MyModelCreate(CreateView): model = MyModel success_url = reverse('path.to.your.create.view') 
+1
source

Source: https://habr.com/ru/post/1205503/


All Articles