Skip to content

Instantly share code, notes, and snippets.

@ChillarAnand
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save ChillarAnand/c6b147202c3c4dece63c to your computer and use it in GitHub Desktop.

Select an option

Save ChillarAnand/c6b147202c3c4dece63c to your computer and use it in GitHub Desktop.
django gotcha #1
In [1]: from django import forms
In [2]: class SampleForm(forms.Form):
...: name = forms.CharField(max_length=10, initial='avil page')
...:
In [3]: f = SampleForm()
In [4]: f.as_p()
Out[4]: u'<p>Name: <input maxlength="10" name="name" type="text" value="avil page" /></p>'
In [11]: from django import forms
In [12]: class AdvancedForm(forms.Form):
....:
....: def __init__(self, *args, **kwargs):
....: super().__init__(*args, **kwargs)
....: self.fields['name'].initial = 'override'
....:
....: name=forms.CharField(max_length=10)
....:
In [13]: f2 = AdvancedForm()
In [14]: f2.as_p()
Out[14]: '<p>Name: <input maxlength="10" name="name" type="text" value="override" /></p>'
In [11]: from django import forms
In [12]: class AdvancedForm(forms.Form):
....:
....: def __init__(self, *args, **kwargs):
....: super().__init__(*args, **kwargs)
....: self.fields['name'].initial = 'override' # don't try this at home
....:
....: name=forms.CharField(max_length=10)
....:
In [19]: f3 = AdvancedForm(initial={'name': 'precedence'})
In [20]: f3.as_p()
Out[20]: '<p>Name: <input maxlength="10" name="name" type="text" value="precedence" /></p>'
In [21]: from django import forms
In [22]: class AdvancedForm(forms.Form):
....:
....: def __init__(self, *args, **kwargs):
....: super().__init__(*args, **kwargs)
....: self.initial['name'] = 'override' # aha!!!!
....:
....: name=forms.CharField(max_length=10)
....:
In [23]: f4 = AdvancedForm(initial={'name': 'precedence'})
In [24]: f4.as_p()
Out[24]: '<p>Name: <input maxlength="10" name="name" type="text" value="override" /></p>'
data = self.field.bound_data(
self.data,
self.form.initial.get(self.name, self.field.initial) # precedence matters!!!!
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment