2016-03-27 76 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。它仍然在那里。我试图进行迁移和迁移,但仍然是同样的问题。 –