There is a case where you want to control the items that can be selected according to the authority of the logged-in user for the list box that is referenced by the master.
↓ A memo of how to investigate and try using the model and form as a sample.
models.py
class Book(models.Model):
name = models.charField('name',max_length=255)
forms.py
class SampleForm(forms.Form):
book = forms.ModelChoiceField(label='book',queryset=Book.objects.all())
Probably the simplest way.
python
form = SampleForm()
form.fields['book'].queryset = Book.objects.filter(...)
__init__
of the formforms.py
class SampleForm(forms.Form):
book = forms.ModelChoiceField(label='book',queryset=Book.objects.none())
def __init__(self, queryset=None, *args, **kwargs):
super(SampleForm,self).__init__(*args,**kwargs)
if queryset :
self.fields['book'].queryset = queryset
python
form = SampleForm(queryset=Book.objects.filter(...))
Note that self.fields
will not be generated unless you call super.__ init__
.
What to do with the default queryset depends on the role of the form.
It is also possible to implement that the queryset itself is not received, only the data used for the filter condition is received, and the queryset is generated on the form side.
forms.py
class SampleForm(forms.Form):
book = forms.ModelChoiceField(label='book',queryset=Book.objects.none())
def __init__(self, permission=None, *args, **kwargs):
super(SampleForm,self).__init__(*args,**kwargs)
self.fields['book'].queryset = self.get_book_list(permission)
def get_book_list(self, permission=None):
if not permission :
return Book.objects.none()
if permission == AAA :
query = Q(...)
elif permission == BBB :
query = Q(...)
#Write as much as you need...
return Book.objects.filter(query)
What you are doing is essentially the same.
The point is that you can overwrite Form.fields ['field_name']. Queryset
after processing Form.__ init__
.
By playing with Form.fields
, you can change various attributes of other fields after the form is created.
Is it possible to add / remove the field itself?
Recommended Posts