Reputation: 984
I have a form, that calls itself and displays a result at the bottom. I want the form to be filled with the data from the previous POST request from the same form, so that I do not have to type in the same data again, after submitting it.
This took me some time to figure out, so I'll self answer this yet again.
Upvotes: 1
Views: 253
Reputation: 984
It is actually quite simple. The trick is to know which method to put it in. First I tried it in the __init__()
method and the post()
method, without any luck.
The get_intitial()
method does the trick as its name suggests.
There is a dictionary called POST
in the self.request
object of the view. You can just get the data from there and put it into the self.initial
dictionary, and that's it. In the example I use three fields: text, name and publication.
class MyFormView(FormView):
template_name = 'form_template.jinja2'
form_class = MyForm
def get_initial(self):
super().get_initial()
if self.request.POST:
self.initial["text"] = self.request.POST.get("text")
self.initial["name"] = self.request.POST.get("name")
self.initial["publication"] = self.request.POST.get("publication")
return self.initial.copy()
Upvotes: 1