[Fixed]-How to set form field value – django

27👍

In your view, if it is a class-based view, do it like so:

class YourView(FormView):
    form_class = YourForm

    def get_initial(self):
        # call super if needed
        return {'fieldname': somevalue}

If it is a generic view, or not a FormView, you can use:

form = YourForm(initial={'fieldname': somevalue})

13👍

There are multiple ways to provide initial data in django form.
At least some of them are:

1) Provide initial data as field argument.

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all(), initial='Munchen')

2) Set it in the init method of the form:

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        self.fields['location'].initial = 'Munchen'

3) Pass a dictionary with initial values when instantiating the form:

#views.py
form = CityForm(initial={'location': 'Munchen'})

In your case, I guess something like this will work..

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        if City.objects.all().exists():
            self.fields['location'].initial = ''
        else:
            self.field['location'].initial = City.objects.all()[:1]

That all is just for demonstration, you have to adapt it to your case.

0👍

To expand on Alexander’s answers, if you wanted to pass multiple values to the form during its initialization, you can pass the data as a dictionary to your Form class constructor (see Django docs:

data = {'fieldname1': somevalue1,
        'fieldname2': somevalue2,
        'fieldname3': somevalue3}
form = YourForm(data)

Leave a comment