Django: initial values for a bound form

Daniel Chvatik
Sep 2, 2016 · 1 min read

I ran into a small issue with Django today: what do you do when you need initial values in a bound form (such as a search form that is both initialized and then processed via GET action (so that searches can be bookmarked)?

My first thought was to use ‘initial’ in some form, but that turns out not to work according to the docs:

This is why initial values are only displayed for unbound forms. For bound forms, the HTML output will use the bound data.

Stack Overflow had a few answers, but they were either very clunky (if you have a lot of forms and default values), didn’t work or just were not very elegant:

The solution? It’s simple once you think about it, don’t bind the form unless you actually need to:

Only bind the form if there is submitted data, otherwise just use ‘initial’ for the form data

Apollo Data Solutions Blog

Web development and entrepreneurship

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store