Django,用密码确认更新用户配置文件

时间:2016-05-07 11:30:28

标签: python django django-forms

所以,我想让我的用户编辑他的个人资料。

用户有用户名,电子邮件和图片。

此外,我希望用户在编辑他的个人资料时确认他的密码,以及我的问题所在。

看起来像那样

enter image description here

而不是检查我的密码并更新用户名和/或电子邮件和/或图片我的程序更新所有内容。更新后,密码被破坏。

forms.py

class UpdateProfile(forms.ModelForm):
    username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)),
                                label=_("Username"), error_messages={
            'invalid': _("This value must contain only letters, numbers and underscores.")})
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
    password = forms.CharField(
        widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
    picture = forms.ImageField(required=False)

    class Meta:
        model = Person
        fields = ('username', 'email', 'password', 'picture')

    def clean_username(self):
        if self.initial['username'] == self.cleaned_data['username']:
            return self.cleaned_data['username']
        try:
            user = Person.objects.get(username__iexact=self.cleaned_data['username'])
        except Person.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_("The username already exists. Please try another one."))

    def clean_email(self):
        email = self.cleaned_data["email"]
        if self.initial['email'] == email:
            return email
        try:
            gg = Person.objects.get(email=email)
        except Person.DoesNotExist:
            return email
        print("DUPLICATE")
        raise forms.ValidationError('duplicate email')

    def clean(self):
        if 'password' in self.cleaned_data :
            p =Person.objects.get(username__iexact=self.initial['username'])
            if not p.check_password(self.cleaned_data['password']):
                raise forms.ValidationError(_("Password is wrong."))
        return self.cleaned_data

views.py

def edit(request):
    args = {}
    args.update(csrf(request))
    if request.method == 'POST':
        user_form = UpdateProfile(request.POST, request.FILES, instance=Person.objects.get_by_natural_key(request.user.get_username()))
        args['user_form'] = user_form
        if user_form.is_valid():
            user_form.save()
            return HttpResponseRedirect('/profile/')
    args['user_form'] = UpdateProfile(request.POST or None)
    args['user2'] = Person.objects.get_by_natural_key(request.user.get_username())
    return render_to_response('edit.html', args, context_instance=RequestContext(request))

在html中我有默认表单。

我认为问题在于UpdateProfile中有密码字段。但是,我不知道如何使其发挥作用。

1 个答案:

答案 0 :(得分:0)

class Meta:
        model = Person
        fields = ('username', 'email', 'picture')

我从字段中删除了密码,现在它正在运行。我不知道这是否是我问题的正确解决方案,但它确实有效。