M
Marc Aymerich
Hi!
I need to create a pretty complex class at runtime. something like
this one:
(note: "...." means that the number of attributes can be variable)
class VirtualUserLimitForm(ModelForm):
swap_limit = forms.CharField(max_length=100,
initial=monitor1.default_limit)
memory_limit = forms.CharField(max_length=100,
initial=monitor2.default_limit)
...
class Meta:
model = model
def __init__(self, *args, **kwargs):
super(VirtualUserLimitForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['swap_limit'].initial =
kwargs['instance'].monitoring.filter(monitor=monitor1)[0].current
self.fields['memory_limit'].initial =
kwargs['instance'].monitoring.filter(monitor=monitor2)[0].current
...
I can generate all the needed code as string and then use exec(), but
it seems ugly to me. I'm wondering if there is another way more
elegant to do that? metaclasses maybe? What is your recommendation?
Thanks!!
I need to create a pretty complex class at runtime. something like
this one:
(note: "...." means that the number of attributes can be variable)
class VirtualUserLimitForm(ModelForm):
swap_limit = forms.CharField(max_length=100,
initial=monitor1.default_limit)
memory_limit = forms.CharField(max_length=100,
initial=monitor2.default_limit)
...
class Meta:
model = model
def __init__(self, *args, **kwargs):
super(VirtualUserLimitForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['swap_limit'].initial =
kwargs['instance'].monitoring.filter(monitor=monitor1)[0].current
self.fields['memory_limit'].initial =
kwargs['instance'].monitoring.filter(monitor=monitor2)[0].current
...
I can generate all the needed code as string and then use exec(), but
it seems ugly to me. I'm wondering if there is another way more
elegant to do that? metaclasses maybe? What is your recommendation?
Thanks!!