Created
June 12, 2013 17:17
-
-
Save pipermerriam/5767274 to your computer and use it in GitHub Desktop.
An example of sending a password reset email in django as a class-based email.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urlparse import urljoin | |
from django.contrib.auth.tokens import default_token_generator | |
from django.utils.http import int_to_base36 | |
from django.contrib.sites.models import Site | |
from django.core.urlresolvers import reverse | |
from emailtools import MarkdownEmail | |
class BuildAbsoluteURIMixin(object): | |
use_https = False | |
def get_site(self): | |
return Site.objects.get_current() | |
def reverse_absolute_uri(self, view_name, args=None, kwargs=None): | |
location = reverse(view_name, args=args, kwargs=kwargs) | |
return self.build_absolute_uri(location) | |
def build_absolute_uri(self, location): | |
current_site = self.get_site() | |
current_uri = '{protocol}://{domain}{location}'.format( | |
protocol=('https' if self.use_https else 'http'), | |
domain=current_site.domain, | |
location=location, | |
) | |
return urljoin(current_uri, location) | |
class UserTokenEmailMixin(BuildAbsoluteURIMixin): | |
UID_KWARG = 'uidb36' | |
TOKEN_KWARG = 'token' | |
token_generator = default_token_generator | |
def get_user(self): | |
return self.args[0] | |
def generate_token(self, user): | |
return self.token_generator.make_token(user) | |
def get_uid(self, user): | |
return int_to_base36(user.pk) | |
def reverse_token_url(self, view_name, args=None, kwargs=None): | |
kwargs.setdefault(self.UID_KWARG, self.get_uid(self.get_user())) | |
kwargs.setdefault(self.TOKEN_KWARG, self.generate_token(self.get_user())) | |
return self.reverse_absolute_uri(view_name, args=args, kwargs=kwargs) | |
class PasswordResetEmail(UserTokenEmailMixin, MarkdownEmail): | |
from_email = '[email protected]' | |
template_name = 'accounts/mail/password_reset.html' | |
subject = "Retul: Password Reset" | |
use_https = True | |
def get_to(self): | |
return [self.get_user().email] | |
def get_context_data(self, **kwargs): | |
kwargs = super(PasswordResetEmail, self).get_context_data() | |
user = self.get_user() | |
kwargs.update({ | |
'user': user, | |
'reset_url': self.reverse_token_url('accounts.views.password_reset_confirm'), | |
}) | |
return kwargs | |
password_reset_email = PasswordResetEmail.as_callable() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment