How do I require an inline in the Django Admin?

前端 未结 6 1563
旧巷少年郎
旧巷少年郎 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:29

    I took Carl's advice and made a much better implementation then the hack-ish one I mentioned in my comment to his answer. Here is my solution:

    From my forms.py:

    from django.forms.models import BaseInlineFormSet
    
    
    class RequiredInlineFormSet(BaseInlineFormSet):
        """
        Generates an inline formset that is required
        """
    
        def _construct_form(self, i, **kwargs):
            """
            Override the method to change the form attribute empty_permitted
            """
            form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
            form.empty_permitted = False
            return form
    

    And the admin.py

    class ProfileInline(admin.StackedInline):
        """
        Allows profile to be added when creating user
        """
        model = Profile
        extra = 1
        max_num = 1
        formset = RequiredInlineFormSet
    
    
    class UserProfileAdmin(admin.ModelAdmin):
        """
        Options for the admin interface
        """
        inlines = [ProfileInline]
        list_display = ['edit_obj', 'name', 'username', 'email', 'is_active',
            'last_login', 'delete_obj']
        list_display_links = ['username']
        list_filter = ['is_active']
        fieldsets = (
            (None, {
                'fields': ('first_name', 'last_name', 'email', 'username',
                    'is_active', 'is_superuser')}),
            (('Groups'), {'fields': ('groups', )}),
        )
        ordering = ['last_name', 'first_name']
        search_fields = ['first_name', 'last_name']
    
    
    admin.site.register(User, UserProfileAdmin)
    

    This does exactly what I want, it makes the Profile inline formset validate. So since there are required fields in the profile form it will validate and fail if the required information isn't entered on the inline form.

提交回复
热议问题