Django admin - inline inlines (or, three model editing at once)

泄露秘密 提交于 2019-11-27 02:44:22
Matthew Marshall

You need to create a custom form and template for the LinkSectionInline.

Something like this should work for the form:

LinkFormset = forms.modelformset_factory(Link)
class LinkSectionForm(forms.ModelForm):
    def __init__(self, **kwargs):
        super(LinkSectionForm, self).__init__(**kwargs)
        self.link_formset = LinkFormset(instance=self.instance, 
                                        data=self.data or None,
                                        prefix=self.prefix)

    def is_valid(self):
        return (super(LinkSectionForm, self).is_valid() and 
                    self.link_formset.is_valid())

    def save(self, commit=True):
        # Supporting commit=False is another can of worms.  No use dealing
        # it before it's needed. (YAGNI)
        assert commit == True 
        res = super(LinkSectionForm, self).save(commit=commit)
        self.link_formset.save()
        return res

(That just came off the top of my head and isn't tested, but it should get you going in the right direction.)

Your template just needs to render the form and form.link_formset appropriately.

Django-nested-inlines is built for just this. Usage is simple.

from django.contrib import admin
from nested_inlines.admin import NestedModelAdmin, NestedStackedInline, NestedTabularInline
from models import A, B, C

class MyNestedInline(NestedTabularInline):
    model = C

class MyInline(NestedStackedInline):
    model = B
    inlines = [MyNestedInline,]

class MyAdmin(NestedModelAdmin):
    pass

admin.site.register(A, MyAdmin)

My recommendation would actually be to change your model. Why not have a ForeignKey in Link to LinkSection? Or, if it's not OneToMany, perhaps a ManyToMany field? The admin interface will generate that for free. Of course, I don't recommend this if links don't logically have anything to do with link sections, but maybe they do? If they don't, please explain what the intended organization is. (For example, is 3 links per section fixed or arbitrary?)

You can create a new class, similar to TabularInline or StackedInline, that is able to use inline fields itself.

Alternatively, you can create new admin templates, specifically for your model. But that of course overrules the nifty features of the admin interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!