Example view code:
lazy_field_options = {
'field_name_that_is_m2m': {
'queryset': YourRelatedModel.objects.filter(groups=request.user.groups.all()),
},
'field_name_that_is_fk': {
'queryset': YourOtherRelatedModel.objects.filter(slug=request_slug),
},
}
modelform = YourModelForm(jpic_field_options=lazy_field_options)
# after the modelform has called for parent __init__, it will set
# options for each field if possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | # todo : get a more descriptive FC prefix than "jpic"
class JpicModelForm(forms.ModelForm):
"""
Inherit from this, then use this new keyword argument
'jpic_field_options' with a dict of dicts such as:
{
'field_name_that_is_m2m': {
'queryset': aqueryset,
},
'field_name_that_is_fk': {
'queryset': anotherqueryset,
},
}
This solves the problem of using a queryset made in the view
as choices for a M2M/FK field ...
"""
def __init__(self, *args, **kwargs):
if 'jpic_field_options' in kwargs.keys():
jpic_field_options = kwargs.pop('jpic_field_options')
super(JpicModelForm, self).__init__(*args, **kwargs)
for field, args in jpic_field_options.items():
if field not in self.fields:
continue
for arg, value in args.items():
setattr(self.fields[field], arg, value)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.