How do I set initial form values of CreateView view using POST only (and not GET)?
<p>Users click a button that takes them to a new form via a POST request, which contains a pk. This is used to pre-populate the new form with some extra data. No data has been saved to database at this point. I don't want to pass this pk along the URL so can't call view using GET.</p>

<p>I've tried overriding the <code>get_initial()</code> method in CreateView but this only seems to be called after a GET request.</p>

<p>I've also tried <code>def post()</code> which gives me easy access to the fields but means I have to write more code to handle form validation etc (which is handled automagically by the vanilla CreateView).</p>

<p>So, what's the best way to handle rendering and saving of a form when both requests are made via POST?</p>

<p>What I'd do:</p>

<pre><code>def post(self, request, **kwargs):
    # Replace 'list_of_pets' with stuff that you'll definitely have in the first request
    if 'list_of_pets' in request.POST:
        # Provide initial data for form in get()
        return self.get(request, **kwargs)
    else:
        # Provides automatic form validation
        return super().post(request, **kwargs)
</code></pre>

<p>In the <code>get()</code> method you can set the initial data and whatnot. You could also use a completely separate method, but overriding <code>get()</code> gives you the benefit that if someone wanders to the URL without a POST request, they don't get a nasty 405 right away (of course there are other ways to get avoid that it, just sayin').</p>

python django django-views