manipulate inline form field
for existing instances
Jeder inline instance will have new course field queryset
def instance_form(self, **kwargs):
instance = super(UserCourseRelationshipInline, self).instance_form(**kwargs)
for form in instance:
field = form.fields['course']
field.queryset = Course.objects.filter(mandantcourse__mandant=self.user.mandant)
# field = formset.form.declared_fields['course']
# field.queryset = Course.objects.filter(mandantcourse__mandant=self.user.mandant)
return instance
pass attributes to inline form
form = UserCourseInlineAdminForm
def get_formset(self, **kwargs):
self.form.user = self.request.user
return super(UserCourseRelationshipInline, self).get_formset(**kwargs)
in form.py:
class UserCourseInlineAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserCourseInlineAdminForm, self).__init__(*args, **kwargs)
user = self.user
if hasattr(user, 'mandant'):
mandant = user.mandant
self.fields['course'].queryset = Course.objects.filter(mandantcourse__mandant=mandant)
self.formset
the return value of get_formset is a formset_factory (formset generator), it need to be called to make formset with forms:
RecipeFormset = inlineformset_factory(
Recipe,
RecipeIngredient,
extra=len(recipe_ingredients),
can_delete=False)
formset = RecipeFormset()
for subform, data in zip(formset.forms, recipe_ingredients):
subform.initial = data
return render_to_response('recipes/form_recipe.html', {
'form': form,
'formset': formset,
})
In xadmin the formset is not populated with get_formset, the forms will be populated with instance_form method