【问题标题】:Force the user to add an instance of some InlineModelAdmin when adding a model在添加模型时强制用户添加一些 InlineModelAdmin 的实例
【发布时间】:2012-04-19 11:19:37
【问题描述】:

我有一个UserAdmin,我像这样定义了一个UserProfileInline

from ...  
from django.contrib.auth.admin import UserAdmin as UserAdmin_

class UserProfileInLine(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False
    verbose_name = 'Profile'
    verbose_name_plural = 'Profile'

class UserAdmin(UserAdmin_):
    inlines = [UserProfileInLine]

我的UserProfile 模型有一些必填字段。

我想要的是强制用户不仅输入用户名和重复密码,而且至少输入必填字段,以便创建 UserProfile 实例并将其关联到正在添加的 User .

如果我在创建用户时在UserProfileInline 的任何字段中输入任何内容,它会毫无问题地验证表单,但如果我不触摸任何字段,它只会创建用户并且UserProfile 不会发生任何事情。

有什么想法吗?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    查看最近的答案Extending the user profile in Django. Admin creation of users,需要将inline的formempty_permitted属性设置为False。就像

    class UserProfileForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(UserProfileForm, self).__init__(*args, **kwargs)
            if self.instance.pk is None:
                self.empty_permitted = False # Here
    
        class Meta:
            model = UserProfile
    
    
    class UserProfileInline(admin.StackedInline):                                     
        form = UserProfileForm  
    

    另一个可能的解决方案是创建自己的Formset(继承自BaseInlineFormSet),就像this link 中建议的那样。

    可能是这样的:

    class UserProfileFormset(BaseInlineFormSet):
        def clean(self):
            for error in self.errors:
                if error:
                    return
            completed = 0
            for cleaned_data in self.cleaned_data:
                # form has data and we aren't deleting it.
                if cleaned_data and not cleaned_data.get('DELETE', False):
                    completed += 1
    
            if completed < 1:
                raise forms.ValidationError('You must create a User Profile.')
    

    然后在InlineModelAdmin 中指定该表单集:

    class UserProfileInline(admin.StackedInline):
        formset = UserProfileFormset
        ....
    

    第二个选项的好处是,如果 UserProfile 模型不需要填写任何字段,它仍然会要求您在至少一个字段中输入任何数据。第一种模式没有。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多