[Django]-Django – Dynamically importing a models form

6👍

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()

3👍

Putting the import within a method on the model should be enough to get you around the circular import, so instead of what you have, you’d use:

class SomeModel(models.Model):
    ...
    def get_form(self):
        from someapp.forms import SomeModelForm
        return SomeModelForm

You can even make it a property if you want with:

form = property(get_form)

3👍

There is a built-in func get_model for lazy importing models.

from django.db.models import get_model
SomeModel = get_model('your_app_name', 'SomeModel')

0👍

Using __import__ and getattr.

# models.py
class SomeModel(models.Model):
    ...
    @classmethod
    def get_form(cls):
        try:
            app = __import__(cls._meta.app_label)
            forms = getattr(app, "forms")
            return getattr(forms, "%sForm" % cls.__name__)
        except:
            return None

# forms.py
class SomeModelForm(forms.Form):
    ...

in a view you can get the form associate to a models like this:

# views.p 
from models import SomeModel
...

def myview(request):
    form = SomeModel.getform()

Leave a comment