2012-04-19 1 views
0

私はUserAdminを持っている、と私はこのようなUserProfileInline定義を追加する際に、いくつかのInlineModelAdminのインスタンスを追加するためにユーザーを強制します。私が欲しいものモデル

は、ユーザー名&繰り返しパスワードを入力するようにするだけでなく、UserProfileインスタンスが作成され、追加されているUserに関連しているように、少なくとも必要なフィールドを入力するだけではなく、ユーザーを強制することです。

ユーザー作成時にUserProfileInlineのフィールドに何かを入力すると問題なくフォームが検証されますが、フィールドに触れないとユーザーが作成され、UserProfileは何も起こりません。

どのような考えですか?

答えて

1

最新の回答Extending the user profile in Django. Admin creation of usersを確認するには、インラインの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 

のような別の可能な解決策は、this linkで提案されているように、(それがBaseInlineFormSetから継承)Formset独自に作成することができます。

そのようなことが考えられます。この第二の選択肢の良いところは、のUserProfileモデルが必要としない場合ということです

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

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でそのフォームセットを指定します満たされるフィールドは、少なくとも1つのフィールドにデータを入力するよう依頼します。最初のモードでは表示されません。