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

前端 未结 4 1394
北荒
北荒 2020-11-30 18:19

I\'ve got a set of models that look like this:

class Page(models.Model):
    title = models.CharField(max_length=255)

class LinkSection(models.Model):
    p         


        
4条回答
  •  猫巷女王i
    2020-11-30 18:38

    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.

提交回复
热议问题