基于全局(上下文/会话)变量的Django动态表单

时间:2014-01-03 01:49:39

标签: python django inheritance metaclass

我们已经实现了中间件,告诉我们当前用户的国家/地区代码是什么。我们需要完成的是使用该变量在Django中动态加载特定于国家/地区的表单,然后渲染模板(我们已经找到了模板部分)。这是为了在每次呈现AddressForm(下面)时为不同的国家/地区显示不同的邮政地址表单。

class Address(models.Model):
    address_1 = models.CharField(max_length=128)
    address_2 = models.CharField(max_length=128)
    address_3 = models.CharField(max_length=128)
    city = models.CharField(max_length=128)
    state_province = models.CharField(max_length=64)
    sublocale = models.CharField(max_length=64)
    postal_code = models.CharField(max_length=16)
    zip4 = models.CharField(max_length=4)


class AddressFormUS(ModelForm):
    """Form for United States addresses"""
    class Meta:
        fields = ('address_1', 'address_2', 'city', 'state_province', 'postal_code', 'zip4')

    def __init__(self, *args, **kwargs):
        super(AddressFormUS, self).__init__(*args, **kwargs)
        # Set up labels, required, etc.  specific to the country


class AddressFormAE(ModelForm):
    """Form for United Arab Emirates addresses"""
    class Meta:
        fields = ('address_1', 'address_2', 'address_3', 'city', 'state_province', 'sublocale', 'postal_code', 'zip4')

    def __init__(self, *args, **kwargs):
        super(AddressFormAE, self).__init__(*args, **kwargs)
        # Set up labels, required, etc. specific to the country


class AddressFormMeta(type):
    """Metaclass for AddressForm"""
    def __new__(cls, name, bases, attrs):
         # Retrieve the global country
         country = get_country_code_here()

         # There is a dictionary that contains the country code and corresponding form
         # {'US': AddressFormUS, 'AE': AddressFormAE}
         # We could also use a regex
         form = country_form_dict.get(country)

         return form


class AddressForm(object):
    __metaclass__ = AddressFormMeta


class SomeOtherForm(AddressForm):
    # More fields about the user + address info
    pass

上述问题。它只在首次导入类时加载一次。我需要它根据用户的国家进行更改。在更新以提取正确的国家/地区表单时,我无法弄清楚如何动态继承它。任何想法都会很棒。也许我会以错误的方式解决这个问题,并且某人有更好的方法/建议可行。提前谢谢!

0 个答案:

没有答案