Ejemplo n.º 1
0
 def save(self, *args, **kwargs):
     if not self.verification_key:
         self.verification_key = generate_key(self.user, self.email)
     return super(EmailChangeRequest, self).save(*args, **kwargs)
Ejemplo n.º 2
0
def email_change_view(request, extra_context={},
        success_url='email_verification_sent',
        template_name='email_change/email_change_form.html',
        email_message_template_name='email_change/emails/verification_email_message.html',
        email_subject_template_name='email_change/emails/verification_email_subject.html'):
    """Allow a user to change the email address associated with the user account.


    """
    if request.method == 'POST':
        form = EmailChangeForm(username=request.user.username, data=request.POST, files=request.FILES)
        if form.is_valid():
            
            EmailChangeRequest = cache.get_model('email_change', 'EmailChangeRequest')
            
            email = form.cleaned_data.get('email')
            verification_key = generate_key(request.user, email)
            
            site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME')
            domain = getattr(settings, 'SITE_URL', None)

            if domain is None:
                Site = cache.get_model('sites', 'Site')
                current_site = Site.objects.get_current()
                site_name = current_site.name
                domain = current_site.domain
            
            protocol = 'http'
            if request.is_secure():
                protocol = 'https'
            
            # First clean all email change requests made by this user
            qs = EmailChangeRequest.objects.filter(user=request.user)
            qs.delete()
            
            # Create an email change request
            EmailChangeRequest.objects.create(
                user = request.user,
                verification_key = verification_key,
                email = email
                )
            
            # Prepare context
            c = {
                'email': email,
                'site_domain': domain,
                'site_name': site_name,
                'user': request.user,
                'verification_key': verification_key,
                'protocol': protocol,
            }
            c.update(extra_context)
            context = Context(c)

            # Send success email
            subject = render_to_string(email_subject_template_name, context_instance=context)
            message = render_to_string(email_message_template_name, context_instance=context)
            
            send_mail(subject, message, None, [email])
            
            # Redirect
            return redirect(success_url)
    
    else:
        form = EmailChangeForm(username=request.user.username)
    
    context = RequestContext(request, extra_context)
    context['form'] = form
    
    return render_to_response(template_name, context_instance=context)