Django set default form values
To pre-fill a Django form field, set its initial
attribute within the __init__
method. This snippet plants 'default_text'
as the initial value for field_name
.
Drop this into your form's definition for a swift kick-off.
Dynamic and invisible: Form values mastering
Dynamic default values setting
Let's say you want to dish out default values dynamically based on, well...dynamic conditions or data. Get it done by overriding the form's __init__
method:
This sneaky move allows you to cherry-pick default values from a user profile or another model instance. Yay, omnipotence!
Hiding fields: Hide and seek for pros
Occasionally, a field should be part of the game but not visible. Enter stage right, HiddenInput widget:
With this trick up your sleeve, the hidden_field
sails with the form, unseen but steadfastly bearing its preset default value.
Holding the fort: Set and retain initial values
User deletion? No worries!
Here's a scenario: a user deletes an initial value from a form, and then submits it. By default, the departed initial value will be lost to the void. Fear not! Use clean_<field>()
to make initial values stick:
Mixing POST data with initial values
During form submission, juggling POST data and initial values is common:
Using this setup, you can fallback to initial data when the form isn't being submitted while handling the info normally when it is.
Custom form fields: Because default is too mainstream
Selectively modifying field attributes and widgets can be quite handy. Use the attrs
parameter within form widgets to tweak the rendered HTML as you wish:
With this, custom_field
carries a placeholder text, stepping up your UX game.
Was this article helpful?