如何使用check_password()?

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

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

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

我该使用.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])

热门问答

脏字过滤只支持 TIMTextElem 消息,对自定义消息无效,请问有接口可以主动检查吗?

学生路人
推荐
您好,脏字检查的内容包括单聊和群组消息(只检查文本消息 TIMTextElem,不支持对自定义消息 TIMCustomElem 的过滤)、群名片、群组资料(群名称、群简介、群公告)用户资料和好友关系链中 bytes 类型的数据(如昵称、好友备注和好友分组等)。目前没有这样的接口喔...... 展开详请

怎么使用rsa?

Tina

腾讯云 · 产品经理 (已认证)

Go Serverless!
推荐
您好,可以在在本地安装rsa module后,将依赖一起打zip包上传SCF运行。https://pypi.org/project/rsa/ 在本地做SCF项目的编辑和部署,推荐您使用tcf cli,更加方便高效。 https://github.com/tencentyun/tc...... 展开详请

5.17 更新的备案材料下载是怎么回事?

为了减少下载错误的核验单模板,官网文档中《网站真实性核验单》下载入口已经下掉,可以按照如下方式操作: 1、在备案流程中——上传资料——核验单环节下载 2、在了解备案的省份、单位性质后,可在工单中提供对应省份的核验单模板给到你。 ... 展开详请

域名在腾讯备的案,解析的腾讯云,现在想把域名解析到别商家的服务器,腾讯云会把备案注销吗?

software微软、谷歌、腾讯、阿里、百度……
推荐

接入商都是有责任对备案进行定期核查的,核查中如果客户在腾讯云进行了备案未解析腾讯云服务器是需要重新解析腾讯云服务器的,否则会被取消接入,反之解析了服务器未进行备案各家接入商也是有相应的限制的,比如:腾讯云对未在腾讯云备案的域名会进行未备案阻断。

对象存储COS有没有日志功能?

Hyman Wang

腾讯云 · 高级产品经理 (已认证)

推荐已采纳

你的cos 是否开通了 CDN 加速,如果开通了CDN 加速,可以去 CDN 的控制台下: (统计分析 --- 监控 )页面下拉到底部,可以通过 URL 查看流量情况。

对象存储里的视频能在线播放么?

Jinqn

腾讯 · 高级工程师 (已认证)

腾讯云COS前端开发
推荐

所属标签

扫码关注云+社区