Hi Stackoverflow people,
I would like to change the m2m widget in the admin pages (and later in the actual django site) to a more user friendly double list (like this one).
I understand that django.contrib.admin.widgets.FilteredSelectMultiple could do this for me. However, I have trouble to get it to work. I have added the code below to my admin.py, but the widget is not changing when I view the model in the admin app.
I have tried to adopt the code from here. Every SupplierProfile should connect to one or more countries from the WorldBorder model (based on the GeoDjango example)
Where is the flaw in the code? I can't see why it would not be displayed. Thank you for your help!
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.gis import admin
from django.utils.translation import ugettext_lazy as _
from apps.profile.models import (UserProfile,
SupplierProfile)
from apps.gis_data.models import WorldBorder
class WorldBorderAdmin(admin.ModelAdmin):
filter_horizonal = ('name',)
class SupplierProfileAdminForm(forms.ModelForm):
distribution_location_country = forms.ModelMultipleChoiceField(
queryset = WorldBorder.objects.all(),
required = False,
widget = FilteredSelectMultiple(
verbose_name = _('Distribution Country'),
is_stacked=False
)
)
class Meta:
model = SupplierProfile
def __init__(self, *args, **kwargs):
super(SupplierProfileAdminForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['distribution_location_country'].initial = self.instance.distribution_location_country.all()
def save(self, commit=True):
profile = super(SupplierProfileAdminForm, self).save(commit=False)
profile.distribution_location_country = self.cleaned_data['distribution_location_country']
if commit:
profile.save()
profile.save_m2m()
return profile
class SupplierProfileAdmin(admin.ModelAdmin):
form = SupplierProfileAdminForm
admin.site.register(SupplierProfile, admin.OSMGeoAdmin)
Updated code of admin.py
Is it possible to define the double list as stated below? "distribution_location_country" is the m2m field in my SupplierProfile. For some reason, it is still not coming through.
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.gis import admin
class SupplierProfileAdmin(admin.OSMGeoAdmin):
filter_horizontal = ('distribution_location_country', )
admin.site.register(SupplierProfile, SupplierProfileAdmin)