In django admin how do I add a field for the reverse side of a ManyToManyField -
i have 2 models, 'product' , 'range', linked many many field. 'product' class in app didn't write, can't modified (i can edit modeladmin tho). want have 'ranges' 'product' in editable in admin, , want filteredselectmultiple, not inline admin.
simplified 'models.py':
class product(models.model): name = models.charfield(max_length=64) #etc... #i can't modify class class range(models.model): name = models.charfield(max_length=32) products = models.manytomanyfield(product, related_name='ranges')
and admin.py:
class productadmin(admin.modeladmin): # set here multi-select box ranges? # preferrably 1 of 'add' buttons popup window # add together ranges.
if modify products set manytomanyfield on using existing through table, , works fine, stated can't (or won't it'll create upgrades external app real pain).
thanks in advance help! (ps hope easy see here why don't want utilize inline admin forms - makes ui unnecessarily complex).
sorry may little late, googling may benefit answer. it's not easy, feasible. have build own form (which may descend existing form, if want), , manually load , save items.
from django import forms django.contrib import admin class productform(forms.modelform): # <- own fields declaration ranges = forms.modelmultiplechoicefield( label='ranges', queryset=range.objects.all(), required=false, widget=admin.widgets.filteredselectmultiple("ranges", is_stacked=false)) class meta: model = product class myproductadmin(admin.modeladmin): def save_model(self, request, obj, form, change): # save first obtain id super(myproductadmin, self).save_model(request, obj, form, change) # clean , re-add related objects obj.range_set.clear() range in form.cleaned_data['ranges']: obj.range_set.add(range) def get_form(self, request, obj=none, **kwargs): if obj: productform.base_fields['ranges'].initial = [o.pk o in obj.range_set.all()] else: productform.base_fields['ranges'].initial = [] homecoming productform # unregister , register 1 time again admin.site.unregister(product) admin.site.register(product, myproductadmin)
django django-admin
No comments:
Post a Comment