Search code examples
djangoforms

django forms: default values for bound forms


With this form:

class Form(forms.Form):
    name = forms.CharField(required=False, initial='Hello world')

If I do something like this in the view:

form = Form(request.GET)
if form.is_valid():
    name = form.cleaned_data['name']

Then initial value of name is lost even if request.GET does not contain name as key. Is there any workaround? I would like initial values work to bound forms as "default values".


Solution

  • By slightly modifying Gonzalo's solution, this is the right way:

    class Form(forms.Form):
        name = forms.CharField(required=False, initial='Hello world')
    
        def clean_name(self):
            if not self['name'].html_name in self.data:
                return self.fields['name'].initial
            return self.cleaned_data['name']
    

    If you need this, you may have a look at django-filter app. I have discovered it quite recently.