Explain Codes LogoExplain Codes Logo

Django set default form values

python
form-handling
default-values
user-input
Nikita BarsukovbyNikita Barsukov·Aug 19, 2024
TLDR

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.

class YourForm(forms.Form): field_name = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['field_name'].initial = 'default_text'

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:

class DynamicForm(forms.ModelForm): class Meta: model = YourModel fields = ['dynamic_field'] def __init__(self, user=None, *args, **kwargs): super().__init__(*args, **kwargs) # Because we're better than a Magic-8 ball... if user: self.fields['dynamic_field'].initial = user.profile.default_value

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:

class HiddenForm(forms.Form): hidden_field = forms.CharField(widget=forms.HiddenInput(), initial='invisible_default') def __init__(self, hide_value='none', *args, **kwargs): super().__init__(*args, **kwargs) # Kaboom! Harry Potter-style invisibility… if hide_value: self.fields['hidden_field'].initial = hide_value

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:

class StickyForm(forms.ModelForm): class Meta: model = YourModel fields = ['sticky_field'] def clean_sticky_field(self): # Just like stubborn glitter, it stays! data = self.cleaned_data['sticky_field'] or self.fields['sticky_field'].initial return data

Mixing POST data with initial values

During form submission, juggling POST data and initial values is common:

form = SomeModelForm(request.POST or None, initial={'some_field': 'some_value'})

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:

class CustomForm(forms.ModelForm): class Meta: model = YourModel fields = ['custom_field'] widgets = { 'custom_field': forms.TextInput(attrs={'placeholder': 'Enter a value'}) }

With this, custom_field carries a placeholder text, stepping up your UX game.