2016-03-27 12 views
3

インスタンスからビューで作成されたフォームからいくつかのフィールドを除外する方法は? ユーザ名や電話番号などの属性を編集できるようにしたいが、このフォームではパスワードを変更しないでください。オブジェクトで事前入力されたフォームからフィールドを除外する方法

del user_profile_form.fields['telephone'] 

をしかし、私はそれを行うときには、CSRF token missing or incorrect.提起:

私はこれを試してみました。

@login_required 
def edit_profile(request): 
    user = request.user 
    user_form = UserForm(instance=user) 
    user_profile_form = UserProfileForm(instance=user.userprofile) 

    context = {'user_form': user_form, 
       'user_profile_form': user_profile_form} 

    return render(request, 'auth/profiles/edit-profile.html', context=context) 

FORMS.PY

class UserForm(forms.ModelForm): 
    password1 = forms.CharField(widget=forms.PasswordInput()) 
    password2 = forms.CharField(widget=forms.PasswordInput()) 

    class Meta: 
     model = User 
     fields = ('username', 'email', 'password1','password2', 'first_name', 'last_name') 

    def clean(self): 
     password1 = self.cleaned_data.get('password1') 
     password2 = self.cleaned_data.get('password2') 

     if password1 and password1 != password2: 
      raise forms.ValidationError("Passwords don't match") 

     return self.cleaned_data 

class UserProfileForm(forms.ModelForm): 
    class Meta: 
     model = UserProfile 
     fields = ('telephone','marital_status','how_do_you_know_about_us') 

MODELS.PY

class UserProfile(models.Model): 
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile') 

    # ATRIBUTY KTORE BUDE MAT KAZDY 
    telephone = models.CharField(max_length=40,null=True) 

    HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
      ('coincidence',u'It was coincidence'), 
      ('relative_or_friends','From my relatives or friends'), 
      ) 
    how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True) 

    MARITAL_STATUS_CHOICES = (
     ('single','Single'), 
     ('married','Married'), 
     ('separated','Separated'), 
     ('divorced','Divorced'), 
     ('widowed','Widowed'), 
    ) 
    marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True) 

    # OD KIAL STE SA O NAS DOZVEDELI 
    # A STAV 

    def __unicode__(self): 
     return '{} {}'.format(self.user.first_name,self.user.last_name) 

    def __str__(self): 
     return '{} {}'.format(self.user.first_name,self.user.last_name) 

NEW VIEW

@login_required 
def edit_profile(request): 
    user = request.user 
    if request.method == 'POST': 
     user_form = UserForm(request.POST) 
     user_profile_form = UserProfileForm(request) 
     if user_form.is_valid() and user_profile_form.is_valid(): 
      user_form.save() 
      user_profile_form.save() 
      return HttpResponseRedirect('/logged-in') 
     else: 
      print user_form.errors 
      print user_profile_form.errors 

    else: 
     user_form = UserForm(instance=user) 
     user_profile_form = UserProfileForm(instance=user.userprofile) 
     temp_user_profile_form = deepcopy(user_profile_form) 
     del temp_user_profile_form.fields['password1'] 
     del temp_user_profile_form.fields['password2'] 
    context = {'user_form': user_form, 
       'user_profile_form': temp_user_profile_form} 

    return render(request, 'auth/profiles/edit-profile.html', context=context) 

ERROR

Exception Type: KeyError 
Exception Value:  
'password1' 
+0

テンプレートに '{%csrf_token%}'を含めましたか?テンプレートコードを投稿すると役立つかもしれません。また、forms.pyコード –

+0

@CurtisOlsonを投稿してください。一度だけだったので、それは機能します。電話の削除は機能しましたが、パスワード1(追加コード)を削除しようとすると例外が発生します –

答えて

1

あなたはUserFormモデルフォームのためにあなたのMetaクラスでpassword1password2を参照しているように見えます。これらはユーザーモデルのフィールドではないため、削除する必要があります。だから、変更後、あなたのUserFormは次のようになります。

class UserForm(forms.ModelForm): 
    # These 2 fields are unbound fields... 
    password1 = forms.CharField(widget=forms.PasswordInput()) 
    password2 = forms.CharField(widget=forms.PasswordInput()) 

    class Meta: 
     model = User 
     # These fields are your User model's fields 
     fields = ('username', 'email', 'first_name', 'last_name') 

    def clean(self): 
     password1 = self.cleaned_data.get('password1') 
     password2 = self.cleaned_data.get('password2') 

     if password1 and password1 != password2: 
      raise forms.ValidationError("Passwords don't match") 

     return self.cleaned_data 

あなたがビューでそれらを削除する必要はありません。テンプレートで除外するだけです。

さらに、必要に応じてフォームの非表示入力をフォームの__init__メソッドで行うことができます。私はこのアプローチをお勧めします。

+0

Curtisありがとうございます。 edit-profileからpassword1またはpassword2を除外します。それはまだそこにある。私は移行と移行を試みましたが、それと同じ問題です。 –

関連する問題