Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Dynamically importing a models form

Tags:

django

I want to create a view that is able to show a ModelForm for various different models. It does this by obtaining the content type of the model and then dynamically instantiating the model form associated with that particular model. Here is my model:

from django.db import models

class SomeModel(models.Model):
    name = models.CharField(max_length=150)

    def __unicode__(self):
        return self.name

And inside the same app there is a forms.py with the following form:

from django.forms import ModelForm

from someapp.models import SomeModel 

class SomeModelForm(ModelForm):
    class Meta:
        model = SomeModel
        fields = ('name',)

So what I want to do inside of my view file is return the correct form for each model dynamically. I tried the following:

from django.db import models
from someapp.forms import SomeModelForm

    class SomeModel(models.Model):
        name = models.CharField(max_length=150)

        form = SomeModelForm

        def __unicode__(self):
            return self.name

But it doesn't work because of the obvious circular import. Does anyone have any idea how I might go about achieving this? I tried toying with modelform_factory, but it seems to ignore any of my custom model forms in forms.py.

EDIT: I should of mentioned that I won't have an instance of the model, just the model class itself, so having a method that inside of the model doesn't work (it does, however, work if you are calling it on an instance of the model)

like image 594
Hanpan Avatar asked Sep 05 '26 04:09

Hanpan


1 Answers

You could get around the circular import by importing your model form inside a method.

class SomeModel(models.Model):
    name = models.CharField(max_length=150)

    @staticmethod
    def get_form_class():
        from someapp.forms import SomeModelForm
        return SomeModelForm

# in your view:
SomeModel.get_form_class()
like image 63
Alasdair Avatar answered Sep 07 '26 21:09

Alasdair