在djangoform中动态填充值

1 投票
2 回答
1007 浏览
提问于 2025-04-16 14:09

问题详情:

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] 这个模型里有一个国家,网页上是一个下拉列表,还有一个城市,目前在网页上是一个文本框。

这个模型的表单长得像这样:

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”里;城市的文本框显示用户的城市,这个城市的名字保存在变量“users_city”里。

谢谢,

2 个回答

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

撰写回答