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)
- [Django]-Django_crontab not working on production docker
- [Django]-Why does MySQL treat Japanese alphabets hiragana and katakana the same, and how can you make it compatible with Django?
- [Django]-Using `defer` or `only` on ForeignKey
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')
- [Django]-How to use filter_horizontal on a ForeignKey between two apps using ContentTypes in Django admin?
- [Django]-How can I pass values/parameters from HTML to Django Views?
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()
- [Django]-Why does the Django Atom1Feed use atom:updated instead of atom:published?
- [Django]-Django Serializer returns JSON for parent class objects only and leave child objects as same?
- [Django]-Django mail sending error with DEBUG=False
Source:stackexchange.com