I have a model called Keyword
and a model called Statement
, and I've been customizing the form for adding or changing statements. Each Keyword
object has an m2m (many to many) relationship with Statement
objects, and I wanted users to be able to select keywords to associate. The default widget for m2m fields isn't useful in my case because there are many Keyword objects so I needed something better than that. I used the FilteredSelectMultiple
widget in order to get the adjustments I needed.
Here's the code for that.
In admin.py
class KeywordInline(admin.TabularInline):
model = Keyword.statement.through
class StatementAdmin(admin.ModelAdmin):
list_display = ('statement_id', 'title', 'author', 'released_by', 'issue_date', 'access', 'full_text',)
list_filter = (StatementListFilter, 'released_by', 'issue_date', 'access',)
search_fields = ('statement_id', 'title', 'author', 'issue_date',)
inlines = [ KeywordInline,]
in forms.py
class StatementForm(forms.Modelform):
statement_keywords = forms.ModelMultipleChoiceField(
queryset=Keyword.objects.all(),
required=False,
widget=FilteredSelectMultiple(
verbose_name='Keywords Associated with Statement',
is_stacked=False
)
)
class Meta:
model = Statement
def __init__(self, *args, **kwargs):
super(StatementForm, self).__init__(*args, **kwargs)
if self.instance.pk:
self.fields['statement_keywords'].initial = self.instance.keyword_set.all()
def save(self, commit=True):
statement = super(StatementForm, self).save(commit=False)
if commit:
statement.save()
if statement.pk:
statement.keyword_set = self.cleaned_data['keyword']
self.save_m2m()
return statement
So now I have a filter_horizontal menu for my inline, just like I wanted. But there's one problem: There's no plus sign to add new keywords.
I know that the RelatedFieldWidgetWrapper
is necessary to resolve this, and I've found tons of examples of people using it. However, I haven't been able to find one that suits my situation. The most immediate problem I'm having right now is trying to insert something into the "rel" parameter. The "rel" parameter typically defines "a relation of the two models involved," going off of this popular example implementation: http://dashdrum.com/blog/2012/07/relatedfieldwidgetwrapper/
I don't know what to indicate for this relation nor how to indicate it because I'm working with an inline. So I'm not actually working with a field called "keywords," I am doing a reverse look up of the m2m relationship between Keyword
and Statement
. So I don't know what the name could be to describe the relationship.
All of the examples I've found haven't really talked about what to do in this situation. Most examples easily get the field of interest from one of the models and then get its type or relationship, but with an inline model and a reverse relation I can't necessarily do that.