2011-03-22 125 views
1

問題的詳細信息: 1]我有一個看起來像下面的模型在djangoform動態填充值

class UserReportedData(db.Model): 
    #country selected by the user, this will also populate the drop down list on the html page 
    country = db.StringProperty(choices=['Afghanistan','Aring land']) 
    #city selected by the user 
    city = db.StringProperty() 
    #date and time when the user reported the site to be down 
    date = db.DateTimeProperty(auto_now_add=True) 

2]這種模式有一個國家,這是一個下拉列表中的HTML頁面,城市,是目前在HTML頁面中的文本字段

該模型的形式如下所示:

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 = city_country_dictionary['city'] 

     #using the model with the default country being users conutry and default city being users city 
     model = UserReportedData(default={'country':users_country_name}) 

3]類geoiplocator用於查找用戶國家和城市。

問題:

1]我希望國家下拉列表中顯示的用戶的國家這是在變量「users_country_name」 和城市文本字段,以顯示用戶的城市,這是在varialble「users_city 「

感謝,

回答

2

通常,你可以重寫__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

你可以用窗體類的函數裏面,然後在你看來只是調用這個函數。

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 
+0

感謝@Spike做到這一點,我會嘗試這種解決方案今晚將發佈結果。 – bhavesh 2011-03-22 11:28:46