Can I make a model know about its ModelForm?
I have a standard Model and ModelForm set-up. I want to be able to return the ModelForm object from my Model. This involves an impossible circular reference. I thought that since Django allows foreign key models to be expressed as strings, perhaps it's possible to do something similar. At the moment I'm doing this:
class Thing(models.Model):
stuff = models.TextField()
def get_form(self):
return getattr(sys.modules[__name__], "ThingForm")(self)
class ThingForm(ModelForm):
clas开发者_JAVA技巧s Meta:
model = Thing
It works. But I feel that in doing this I bring shame upon myself and my family. There must be a more honourable way.
By the way, I want do to this because I'm using ContentTypes to create generic foreign keys, so my view code doesn't know what class the model is in the static context.
That's... not an impossible circular reference. Names are only looked up when the code that references them is run.
class Thing(models.Model):
stuff = models.TextField()
def get_form(self):
return ThingForm(self)
class ThingForm(ModelForm):
class Meta:
model = Thing
精彩评论