如何使用check_password()?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1294)

我有以下表格。在用户更改电子邮件前,我如何再次检查用户的密码。即使是他登录的,我想确定它是真正的用户。。

我该使用.check_password()怎么办?

    'EmailChangeForm' object has no attribute 'user'

    /home/craphunter/workspace/project/trunk/project/auth/user/email_change/forms.py in clean_password, line 43

from django import forms
from django.db.models.loading import cache
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User


class EmailChangeForm(forms.Form):

    email = forms.EmailField(label='New E-mail', max_length=75)
    password = forms.CharField(widget=forms.PasswordInput)

    def __init__(self, user, *args, **kwargs):
        super(EmailChangeForm, self).__init__(*args, **kwargs)
        self.user = user

    def clean_password(self):
        valid = self.user.check_password(self.cleaned_data['password'])
        if not valid:
            raise forms.ValidationError("Password Incorrect")
        return valid

    def __init__(self, username=None, *args, **kwargs):
        """Constructor.

        **Mandatory arguments**

        ``username``
            The username of the user that requested the email change.

        """
        self.username = username
        super(EmailChangeForm, self).__init__(*args, **kwargs)

    def clean_email(self):
        """Checks whether the new email address differs from the user's current
        email address.

        """
        email = self.cleaned_data.get('email')

        User = cache.get_model('auth', 'User')
        user = User.objects.get(username__exact=self.username)

        # Check if the new email address differs from the current email address.
        if user.email == email:
            raise forms.ValidationError('New email address cannot be the same \
                as your current email address')

        return email
提问于
用户回答回答于

我会重新编写了你的代码:

View:

@login_required
def view(request, extra_context=None, ...):

    form = EmailChangeForm(user=request.user, data=request.POST or None)

    if request.POST and form.is_valid():
        send_email_change_request(request.user,
                                  form.cleaned_data['email'],
                                  https=request.is_secure())
        return redirect(success_url)
    ...

密码验证形式如下:

class EmailChangeForm(Form):
    email = ...
    old_password = CharField(..., widget=Password())

    def __init__(self, user, data=None):
        self.user = user
        super(EmailChangeForm, self).__init__(data=data)

    def clean_old_password(self):
        password = self.cleaned_data.get('password', None)
        if not self.user.check_password(password):
            raise ValidationError('Invalid password')

从View:中提取逻辑:

 def send_email_change_request(user, new_email, https=True):

    site = cache.get_model('sites', 'Site')

    email = new_email
    verification_key = generate_key(user, email)

    current_site = Site.objects.get_current()
    site_name = current_site.name
    domain = current_site.domain

    protocol = 'https' if https else 'http'

    # First clean all email change requests made by this user
    qs = EmailChangeRequest.objects.filter(user=request.user)
    qs.delete()

    # Create an email change request
    change_request = EmailChangeRequest(
       user = request.user,
       verification_key = verification_key,
       email = email
    )
    change_request.save()

    # Prepare context
    c = {
        'email': email,
        'site_domain': 'dev.tolisto.de',
        'site_name': 'tolisto',
        'user': self.user,
        'verification_key': verification_key,
        'protocol': protocol,
    }
    c.update(extra_context)
    context = Context(c)

    # Send success email
    subject = "Subject" # I don't think that using template for 
                        # subject is good idea
    message = render_to_string(email_message_template_name, context_instance=context)

    send_mail(subject, message, None, [email])
用户回答回答于

我觉得你回答了你自己的问题:)

check_password方法的文档在这里:http : //docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.check_password

success = user.check_password(request.POST['submitted_password'])
if success: 
   # do your email changing magic
else:
   return http.HttpResponse("Your password is incorrect") 
   # or more appropriately your template with errors

由于你已经将request.user传入你的表单构造函数,所以您可以将所有逻辑放在表单中,而不会有任何问题。

class MyForm(forms.Form):
     # ...
     password = forms.CharField(widget=forms.PasswordInput)

     def __init__(self, user, *args, **kwargs):
          super(MyForm, self).__init__(*args, **kwargs)
          self.user = user

     def clean_password(self):
         valid = self.user.check_password(self.cleaned_data['password'])
         if not valid:
             raise forms.ValidationError("Password Incorrect")
         return valid

所属标签

可能回答问题的人

  • HKC

    红客学院 · 创始人 (已认证)

    27 粉丝7 提问5 回答
  • 西风

    renzha.net · 站长 (已认证)

    9 粉丝1 提问3 回答
  • 螃蟹居

    1 粉丝0 提问2 回答
  • 富有想象力的人

    2 粉丝0 提问1 回答

扫码关注云+社区

领取腾讯云代金券