次のフォームがあります。ユーザーが最終的にemailadsressを変更する前に、ユーザーからパスワードを再度確認するにはどうすればよいですか。彼がログインしていても、それが本当にユーザーであることを確認したいだけです。ただの安全なことです。
.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
コードを次のようにリファクタリングします。
見る:
@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')
ビューからロジックを抽出します。
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をフォームコンストラクターに渡しているため(独自の理由で___init__
_をオーバーライドしたように見えます)、問題なくすべてのロジックをフォームに配置できます。
_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
_
OK。主な問題は、___init__
_が2回定義されているため、最初のステートメントが役に立たないことです。 2つ目の問題は、本当に必要がないときにuser
に対して複数のクエリを実行することです。
元の質問からかなり外れていますが、これが学習経験であることを願っています。
変更したのはほんのわずかです。
__init__
_定義を削除__init__
_を変更して、テキストではなくUser
インスタンスを受け入れるusername
User.objects.get(username=username)
のクエリを削除しました。_user=request.user
_の代わりにフォームコンストラクタ_username=request.user.username
_を渡すことを忘れないでください
_class EmailChangeForm(forms.Form):
email = forms.EmailField(label='New E-mail', max_length=75)
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(EmailChangeForm, self).__init__(*args, **kwargs)
def clean_password(self):
valid = self.user.check_password(self.cleaned_data['password'])
if not valid:
raise forms.ValidationError("Password Incorrect")
def clean_email(self):
email = self.cleaned_data.get('email')
# no need to query a user object if we're passing it in anyways.
user = self.user
# 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
_
最後に、ここでは優れた実践について説明しているので、_myform.send_confirmation_email
_を呼び出すだけで済むように、現在のビューコードをフォームメソッドに移動することについて、Skirmantasの提案に従うことをお勧めします。
いい運動のようですね!
ゆうじさん、ありがとうございました。最初のdef __init__
に変数userがない場合に機能します。また、def clean_password
の最初の2行をdef clean_email
に追加しました
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, *args, **kwargs):
self.user = user
super(EmailChangeForm, self).__init__(*args, **kwargs)
def clean_password(self):
User = cache.get_model('auth', 'User')
user = User.objects.get(username__exact=self.username)
valid = 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