2016-03-27 72 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) 

錯誤

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

您是否在模板中包含了「{%csrf_token%}」?如果您發佈模板代碼,那可能會有所幫助。此外,請張貼您的forms.py代碼 –

+0

@CurtisOlson它只是一次,然後,它的工作 - 電話刪除工作,但它引發異常,當我嘗試刪除密碼1(添加代碼) –

回答

1

它看起來就像你在你的Meta類引用password1password2UserForm模型形式。這些應該被刪除,因爲它們不是用戶模型中的字段。所以改變後,你的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

柯蒂斯感謝,但這種做法沒有從編輯配置文件中排除password1和password2。它仍然在那裏。我試圖進行遷移和遷移,但仍然是同樣的問題。 –