How do I require an inline in the Django Admin?

前端 未结 6 1559
旧巷少年郎
旧巷少年郎 2020-12-13 09:44

I have the following admin setup so that I can add/edit a user and their profile at the same time.

class ProfileInline(admin.StackedInline):
    \"\"\"
             


        
6条回答
  •  轮回少年
    2020-12-13 10:32

    The easiest and most natural way to do that is via fomset clean():

    class RequireOneFormSet(forms.models.BaseInlineFormSet):
        def clean(self):
            super().clean()
            if not self.is_valid():
                return
            if not self.forms or not self.forms[0].cleaned_data:
                raise ValidationError('At least one {} required'
                                      .format(self.model._meta.verbose_name))
    
    class ProfileInline(admin.StackedInline):
        model = Profile
        formset =  RequireOneFormSet
    

    (Inspired by this Matthew Flanagan's snippet and Mitar's comment below, tested to work in Django 1.11 and 2.0).

提交回复
热议问题