title: Django Dynamic Form Based on Global (context/session) Variable
body: <p>We have implemented middleware which tells us what the country code is for the current user. What we need to accomplish is to use that variable to dynamically load a country-specific form in Django, then render the template (we have the template part figured out). This is for displaying different postal address forms for different countries each time the AddressForm (below) is rendered.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The above poses a problem. It is only loaded once when the class is first imported. I need it to change based on the country of the user. I can't figure out how to dynamically inherit this while updating to pull the correct country form. Any ideas would be awesome. Perhaps I am going about this the wrong way and someone has a better method/suggestion that works. Thanks in advance!</p>