在djangoform中动态填充值

时间:2011-03-22 01:04:42

标签: python django google-app-engine django-forms

问题详情: 1]我有一个如下所示的模型

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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