I'm fairly new to both Python and Django, and I'm in the process of building a small website. I've been experimenting with a dynamic form containing a ModelChoiceField constructed from a QuerySet that is determined by user input. The approach described here works well for me, but I run into trouble if I try to dynamically create a type that inherits from a class that I define within the same file. The reason I tried to do this was that I wanted to override the default form field order by setting the form's fields.keyOrder property.
This is how I tried to do it:
from django import forms
class AbstractForm(forms.Form):
def __init__(self, *args, **kwargs):
super(AbstractForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['choices', 'second', 'third']
class ConcreteFormFactory(object):
@staticmethod
def generate(queryset):
properties = {
'second': forms.CharField(),
'third': forms.CharField(),
'choices': forms.ModelChoiceField(queryset=queryset)
}
return type('ConcreteForm', (AbstractForm,), properties)
However, when I import ConcreteFormFactory in my view and attempt to call its generate() method, I get a NameError telling me that AbstractForm is not defined. I tried importing AbstractForm into the calling context, but to no avail. Since I wasn't able to get this approach to work, I accomplished my goal another way, but I would still like to understand the scoping issue here. How do I make my dynamic class aware of other classes defined in the same file where I create it? This is on Django 1.2 and Python 2.7.1 (I know that's a very old version of Django).
NameError?generate(queryset)to a static method? This may be the issue as static methods are called differently against the class instead of the instance object.class A(object): pass,class AFactory(object): @staticmethod def makeA(): return type('A', (A,), {})works fine for me