11👍
✅
Because you instantiate the fields in the form definition, which is presumably being imported by one of your views.
The field init is the wrong place to do this sort of dynamic initialization, for this exact reason. You want something that is called when the form is initialized: ie, the form’s __init__
.
That said, you don’t actually want to do this at all – you just need to use forms.ModelChoiceField
, which takes a queryset and does the dynamic assignment of choices for you.
class MyForm(ModelForm):
field1 = forms.ModelChoiceField(queryset=ReallyLargeTableModel.objects.all())
1👍
In your example:
class UsesSomething():
field = Something()
The line of code field = Something()
will execute when you import the containing module as Python processes the class definition. This is just how Python works. You can actually put arbitrary code inside a class definition.
module: test.py:
class UsesSomething():
print "wow!"
>>> import test
wow!
- [Django]-Allowing basic html markup in django
- [Django]-Django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join
- [Django]-Serializers in django rest framework with dynamic fields
Source:stackexchange.com