1

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.

1
  • s/from/FormView/ - a FormView is NOT a form. Commented Jun 5, 2020 at 11:28

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

6 Comments

You want to replace if self.request.POST with if self.request.method == "POST" - not that it would change much in this case, but that's the proper way to check the request method (you could have a POST request with no data submitted, in which case request.POST would be empty, hence considered as false in a boolean context).
@brunodesthuilliers Actually what he does is better. This isn't a view function, it's a method of a class based view, in which he wants to fill initial data if data was submitted.
@Melvyn I know this isn't a view function, and I did read the question and fully understand the context, thanks.
@brunodesthuilliers Then don't advise to rely on a side effect condition. The pattern is "if there's data, copy it to initial". You're advising to change it to "if the method is post, then it's likely that there's data, so copy it to initial even if there's nothing there". Which is just bad advice.
@Melvyn "Then don't advise to rely on a side effect condition" => since request.POST should NOT be populated if the method wasn't "POST", testing on the request method instead of the non-emptiness of request.POST _is "relying on a side effect condition" (request.POST being - possibly - populated being a side effect of having a POST request).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.