It is actually quite easy to create your admin form classes dynamically. Something like this should work:
def tagform_factory(filetype):
class TagForm(forms.ModelForm):
m_file = forms.ModelChoiceField(
queryset=ManagedFile.objects.filter(type=filetype)
)
return TagForm
class TagAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
if obj is not None and obj.type is not None:
kwargs['form'] = tagform_factory(obj.type)
return super(TagAdmin, self).get_form(request, obj, **kwargs)
Note that the get_form
method is responsible for building the form class, not the form instance. It is badly named, IMHO.
However, you still need to decide what to do for forms that are used to add new tags, rather than edit existing ones. In that case you do not yet have a type to which you can restrict the dropdown. Maybe there is actually a data modeling problem lurking here? Do you really need the type
field on the Tag
model? Maybe it should just be removed?