2๐
โ
You would normally do this by overriding __init__
from django.forms import ModelForm, ChoiceField
class MyModelForm(ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
geoiplocator_instance = GeoIpLocator()
city_country_dictionary=geoiplocator_instance.get_country_city_dictionary()
users_country_name = city_country_dictionary['country_name']
users_city = city_country_dictionary['city']
# not exactly sure what you wanted to do with this choice field.
# make the country the only option? Pull a list of related countries?
# add it and make it the default selected?
self.fields['country'] = ChoiceField(choices = [(users_country_name, users_country_name),])
self.fields['city'].initial = users_city
0๐
You can wrap the form class inside a function, and then in your view just call this function.
def make_user_reported_data_form(users_city, users_country_name):
class UserReportedDataForm(djangoforms.ModelForm):
class Meta:
#mechanism to get the users country and city
geoiplocator_instance = GeoIpLocator()
city_country_dictionary=geoiplocator_instance.get_country_city_dictionary()
users_country_name = city_country_dictionary['country_name']
users_city = users_city
model = UserReportedData(default={'country':users_country_name})
return UserReportedDataForm
๐คSpike
- [Answered ]-Grunt exec freezes, expecting 0 status code from django collectstatic
- [Answered ]-Add users to groups in Django
- [Answered ]-Form action isn't triggering at all
- [Answered ]-Selenium testing with django gives 'NoneType' object has no attribute 'path'
Source:stackexchange.com