我有一个“帐户”视图,用户可以在其中更改其电子邮件,姓名和密码。要更改他的电子邮件,他必须通过单击确认链接来确认他的电子邮件地址。我的视图代码看起来非常臃肿,我想知道如何改进它并使其更简洁。这是我目前的情况 -
在模型中:
class EmailChangeAuth(models.Model):
auth_key = models.CharField(max_length=42)
user = models.ForeignKey(User)
new_email = models.CharField(max_length=256)
在视图中:
@login_required
def account(request, changed_email=''):
old_email = User.objects.get(username=request.user.username).email
name_message = password_message = email_message = ''
change_name_form = ChangeNameForm(instance=request.user)
change_password_form = PasswordChangeForm(user=request.user)
change_email_form = ChangeEmailForm(instance=request.user)
if request.method == "POST":
if "change_name" in request.POST:
change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user)
if change_name_form.is_valid():
change_name_form.save()
name_message = 'Your name has been changed.'
if "change_password" in request.POST:
change_password_form = PasswordChangeForm(data=request.POST or None, user = request.user)
if change_password_form.is_valid():
change_password_form.save()
password_message = 'Your password has been changed.'
if "change_email" in request.POST:
change_email_form = ChangeEmailForm(data=request.POST or None, instance=request.user)
if change_email_form.is_valid() and request.POST['email'] != old_email:
auth_key = uuid.uuid4()
email_auth = EmailChangeAuth(auth_key=auth_key, new_email=request.POST['email'], user=request.user)
email_auth.save()
subject = "Please confirm your email address"
link = "http://127.0.0.1:8000" + reverse('change_email') + str(auth_key) +'/'
send_mail(
'Please confirm your email address',
'Please click the following link to confirm your email address: \n \n%s' %(link),
settings.DEFAULT_FROM_EMAIL,
[request.POST['email']]
)
email_message = "Please comfirm your email to complete changes."
return render_to_response('userprofile/account.html',
{
'change_name_form': change_name_form,
'old_email': old_email,
'change_email_form': change_email_form,
'change_password_form': change_password_form,
'changed_email': changed_email,
'password_message': password_message,
'name_message': name_message,
'email_message': email_message,},
context_instance=RequestContext(request))
def change_email(request, auth_key):
try:
email_object = EmailChangeAuth.objects.get(auth_key=auth_key)
user = email_object.user
user.email = email_object.new_email
user.save()
changed_email = "Your email has been changed."
email_object.delete()
return account(request, changed_email=changed_email)
except EmailChangeAuth.DoesNotExist:
return account(request)
哪里是开始改进这个大规模视图代码的好地方?
答案 0 :(得分:5)
好吧,您可以将代码拆分为多个视图。
比如def change_email(request, user_id):
和def change_password(request, user_id):
等,而不是一个帐户视图。