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.
- Django AttributeError 'tuple' object has no attribute 'regex'
- Django, REST and Angular Routes
- Django: Filtering on the related object, removing duplicates from the result
- Docker compose for production and development
- Deploying django in a production server
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)
- Could not start uwsgi process
- Merge two fields in one in a Django Rest Framework Serializer
- Django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
- Django admin different inlines for change and add view
- Django Forms: Foreign Key in Hidden Field
Source:stackexchange.com