How To Add Bi-directional Manytomanyfields In Django Admin?
Solution 1:
The workaround I found was to follow the instructions for ManyToManyFields with intermediary models. Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with the necessary ForeignKey.
# models: make sure the naming convention matches what ManyToManyField would createclassReport_LocationGroups(models.Model):
locationgroup = models.ForeignKey(LocationGroup)
report = models.ForeignKey(Report)
# adminclassReportInline(admin.TabularInline):
model = models.Report_LocationGroups
classLocationGroupAdmin(admin.ModelAdmin):
inlines = ReportInline,
Solution 2:
I think yon can combine this sample code (source) wich breaks sync_db
class ItemType(meta.Model):
name = meta.CharField(maxlength=100)
description = meta.CharField(maxlength=250)
properties = meta.ManyToManyField('PropertyType',
db_table='app_propertytype_itemtypes')
class PropertyType(meta.Model):
name = meta.CharField(maxlength=100)
itemtypes = meta.ManyToManyField(ItemType)
with this snippet
classManyToManyField_NoSyncdb(models.ManyToManyField):
def__init__(self, *args, **kwargs):
super(ManyToManyField_NoSyncdb, self).__init__(*args, **kwargs)
self.creates_table = False
to obtain something like
class ItemType(meta.Model):
name = meta.CharField(maxlength=100)
description = meta.CharField(maxlength=250)
properties = meta.ManyToManyField_NoSyncdb('PropertyType',
db_table='app_propertytype_itemtypes')
class PropertyType(meta.Model):
name = meta.CharField(maxlength=100)
itemtypes = meta.ManyToManyField(ItemType)
Disclaimer : this is just a rough idea
Edit: There is probably someting to do with Django's 1.1 Proxy Models
Solution 3:
I think what are you are looking for is admin inlines. In your admin.py you will want to add something like this:
classLocationGroupInline(admin.TabularInline):
model =LocationGroup
classReportAdmin(admin.ModelAdmin):
inlines = [ LocationGroupInline, ]
admin.site.register(Report, ReportAdmin)
admin.site.register(LocationGroup)
There are many options to include in LocationGroupInline if you want to further configure the inline display of the related model. Two of these options are form and formset, which will let you use custom Django Form and FormSet classes to further customize the look and feel of the inline model admin. Using this you can create a simple Form that displays just the multiple choice field you want (except for a M2M field it will not be possible to display as a single drop down, but a multiple select box). For example:
classMyLocationGroupForm(forms.Form):
location = forms.MultipleModelChoiceField(
queryset=LocationGroup.objects.all())
classLocationGroupInline(admin.TabularInline):
model = LocationGroup
form = MyLocationGroupForm
Post a Comment for "How To Add Bi-directional Manytomanyfields In Django Admin?"