Anonymous avatar Anonymous committed 5f3892e

Packaging this up properly

Comments (0)

Files changed (22)

Empty file removed.

forms.py

-"""
-Form and validation code for user registration.
-
-"""
-
-from django import newforms as forms
-from django.contrib.auth.models import User
-
-# I put this on all required fields, because it's easier to pick up
-# on them with CSS or JavaScript if they have a class of "required"
-# in the HTML. Your mileage may vary.
-attrs_dict = { 'class': 'required' }
-
-class RegistrationForm(forms.Form):
-    """
-    Form for registering a new user account.
-    
-    Validates that the password is entered twice and matches,
-    and that the username is not already taken.
-    
-    """
-    username = forms.CharField(max_length=30,
-                               widget=forms.TextInput(attrs=attrs_dict),
-                               label=u'Username')
-    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
-                                                               maxlength=200)),
-                             label=u'Email address')
-    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
-                                label=u'Password')
-    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
-                                label=u'Password (again, to catch typos)')
-    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
-                             label=u'I have read and agree to the Terms of Service')
-
-    def clean_username(self):
-        """
-        Validates that the username is not already in use.
-        
-        """
-        if self.cleaned_data.get('username', None):
-            try:
-                user = User.objects.get(username__exact=self.cleaned_data['username'])
-            except User.DoesNotExist:
-                return self.cleaned_data['username']
-            raise forms.ValidationError(u'This username is already taken. Please choose another.')
-    
-    def clean_password2(self):
-        """
-        Validates that the two password inputs match.
-        
-        """
-        if self.cleaned_data.get('password1', None) and self.cleaned_data.get('password2', None) and \
-           self.cleaned_data['password1'] == self.cleaned_data['password2']:
-            return self.cleaned_data['password2']
-        raise forms.ValidationError(u'You must type the same password each time')
-    
-    def clean_tos(self):
-        """
-        Validates that the user accepted the Terms of Service.
-        
-        """
-        if self.cleaned_data.get('tos', False):
-            return self.cleaned_data['tos']
-        raise forms.ValidationError(u'You must agree to the terms to register')

models.py

-"""
-A registration profile model and associated manager.
-
-The RegistrationProfile model and especially its custom manager
-implement nearly all the logic needed to handle user registration and
-account activation, so before implementing something in a view or
-form, check here to see if they can take care of it for you.
-
-Also, be sure to see the note on RegistrationProfile about use of the
-``AUTH_PROFILE_MODULE`` setting.
-
-"""
-
-import datetime, random, re, sha
-from django.db import models
-from django.template import Context, loader
-from django.contrib.auth.models import User
-from django.contrib.sites.models import Site
-from django.conf import settings
-
-
-class RegistrationManager(models.Manager):
-    """
-    Custom manager for the RegistrationProfile model.
-    
-    The methods defined here provide shortcuts for account creation
-    and activation (including generation and emailing of activation
-    keys), and for cleaning out expired inactive accounts.
-    
-    """
-    def activate_user(self, activation_key):
-        """
-        Given the activation key, makes a User's account active if the
-        activation key is valid and has not expired.
-        
-        Returns the User if successful, or False if the account was
-        not found or the key had expired.
-        
-        """
-        # Make sure the key we're trying conforms to the pattern of a
-        # SHA1 hash; if it doesn't, no point even trying to look it up
-        # in the DB.
-        if re.match('[a-f0-9]{40}', activation_key):
-            try:
-                user_profile = self.get(activation_key=activation_key)
-            except self.model.DoesNotExist:
-                return False
-            if not user_profile.activation_key_expired():
-                # Account exists and has a non-expired key. Activate it.
-                user = user_profile.user
-                user.is_active = True
-                user.save()
-                return user
-        return False
-    
-    def create_inactive_user(self, username, password, email, send_email=True):
-        """
-        Creates a new User and a new RegistrationProfile for that
-        User, generates an activation key, and mails it.
-        
-        Pass ``send_email=False`` to disable sending the email.
-        
-        """
-        # Create the user.
-        new_user = User.objects.create_user(username, email, password)
-        new_user.is_active = False
-        new_user.save()
-        
-        # Generate a salted SHA1 hash to use as a key.
-        salt = sha.new(str(random.random())).hexdigest()[:5]
-        activation_key = sha.new(salt+new_user.username).hexdigest()
-        
-        # And finally create the profile.
-        new_profile = self.create(user=new_user,
-                                  activation_key=activation_key)
-        
-        if send_email:
-            from django.core.mail import send_mail
-            current_domain = Site.objects.get_current().domain
-            subject = "Activate your new account at %s" % current_domain
-            message_template = loader.get_template('registration/activation_email.txt')
-            message_context = Context({ 'site_url': 'http://%s/' % current_domain,
-                                        'activation_key': activation_key,
-                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
-            message = message_template.render(message_context)
-            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
-        return new_user
-    
-    def delete_expired_users(self):
-        """
-        Removes unused profiles and their associated accounts.
-
-        This is provided largely as a convenience for maintenance
-        purposes; if a RegistrationProfile's key expires without the
-        account being activated, then both the RegistrationProfile and
-        the associated User become clutter in the database, and (more
-        importantly) it won't be possible for anyone to ever come back
-        and claim the username. For best results, set this up to run
-        regularly as a cron job.
-        
-        If you have a User whose account you want to keep in the
-        database even though it's inactive (say, to prevent a
-        troublemaker from accessing or re-creating his account), just
-        delete that User's RegistrationProfile and this method will
-        leave it alone.
-        
-        """
-        for profile in self.all():
-            if profile.activation_key_expired():
-                user = profile.user
-                if not user.is_active:
-                    user.delete() # Removing the User will remove the RegistrationProfile, too.
-
-
-class RegistrationProfile(models.Model):
-    """
-    Simple profile model for a User, storing a registration date and
-    an activation key for the account.
-    
-    While it is possible to use this model as the value of the
-    ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
-    so. This model is intended solely to store some data needed for
-    user registration, and can do that regardless of what you set in
-    ``AUTH_PROFILE_MODULE``, so if you want to use user profiles in a
-    project, it's far better to develop a customized model for that
-    purpose and just let this one handle registration.
-    
-    """
-    user = models.ForeignKey(User, unique=True)
-    activation_key = models.CharField(maxlength=40)
-    key_generated = models.DateTimeField()
-    
-    objects = RegistrationManager()
-    
-    class Admin:
-        pass
-    
-    def save(self):
-        if not self.id:
-            self.key_generated = datetime.datetime.now()
-        super(RegistrationProfile, self).save()
-    
-    def __str__(self):
-        return "User profile for %s" % self.user.username
-    
-    def activation_key_expired(self):
-        """
-        Determines whether this Profile's activation key has expired,
-        based on the value of the setting ``ACCOUNT_ACTIVATION_DAYS``.
-        
-        """
-        expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
-        return self.key_generated + expiration_date <= datetime.datetime.now()
Add a comment to this file

registration/__init__.py

Empty file added.

registration/forms.py

+"""
+Form and validation code for user registration.
+
+"""
+
+from django import newforms as forms
+from django.contrib.auth.models import User
+
+# I put this on all required fields, because it's easier to pick up
+# on them with CSS or JavaScript if they have a class of "required"
+# in the HTML. Your mileage may vary.
+attrs_dict = { 'class': 'required' }
+
+class RegistrationForm(forms.Form):
+    """
+    Form for registering a new user account.
+    
+    Validates that the password is entered twice and matches,
+    and that the username is not already taken.
+    
+    """
+    username = forms.CharField(max_length=30,
+                               widget=forms.TextInput(attrs=attrs_dict),
+                               label=u'Username')
+    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
+                                                               maxlength=200)),
+                             label=u'Email address')
+    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
+                                label=u'Password')
+    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
+                                label=u'Password (again, to catch typos)')
+    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
+                             label=u'I have read and agree to the Terms of Service')
+
+    def clean_username(self):
+        """
+        Validates that the username is not already in use.
+        
+        """
+        if self.cleaned_data.get('username', None):
+            try:
+                user = User.objects.get(username__exact=self.cleaned_data['username'])
+            except User.DoesNotExist:
+                return self.cleaned_data['username']
+            raise forms.ValidationError(u'This username is already taken. Please choose another.')
+    
+    def clean_password2(self):
+        """
+        Validates that the two password inputs match.
+        
+        """
+        if self.cleaned_data.get('password1', None) and self.cleaned_data.get('password2', None) and \
+           self.cleaned_data['password1'] == self.cleaned_data['password2']:
+            return self.cleaned_data['password2']
+        raise forms.ValidationError(u'You must type the same password each time')
+    
+    def clean_tos(self):
+        """
+        Validates that the user accepted the Terms of Service.
+        
+        """
+        if self.cleaned_data.get('tos', False):
+            return self.cleaned_data['tos']
+        raise forms.ValidationError(u'You must agree to the terms to register')

registration/models.py

+"""
+A registration profile model and associated manager.
+
+The RegistrationProfile model and especially its custom manager
+implement nearly all the logic needed to handle user registration and
+account activation, so before implementing something in a view or
+form, check here to see if they can take care of it for you.
+
+Also, be sure to see the note on RegistrationProfile about use of the
+``AUTH_PROFILE_MODULE`` setting.
+
+"""
+
+import datetime, random, re, sha
+from django.db import models
+from django.template import Context, loader
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+from django.conf import settings
+
+
+class RegistrationManager(models.Manager):
+    """
+    Custom manager for the RegistrationProfile model.
+    
+    The methods defined here provide shortcuts for account creation
+    and activation (including generation and emailing of activation
+    keys), and for cleaning out expired inactive accounts.
+    
+    """
+    def activate_user(self, activation_key):
+        """
+        Given the activation key, makes a User's account active if the
+        activation key is valid and has not expired.
+        
+        Returns the User if successful, or False if the account was
+        not found or the key had expired.
+        
+        """
+        # Make sure the key we're trying conforms to the pattern of a
+        # SHA1 hash; if it doesn't, no point even trying to look it up
+        # in the DB.
+        if re.match('[a-f0-9]{40}', activation_key):
+            try:
+                user_profile = self.get(activation_key=activation_key)
+            except self.model.DoesNotExist:
+                return False
+            if not user_profile.activation_key_expired():
+                # Account exists and has a non-expired key. Activate it.
+                user = user_profile.user
+                user.is_active = True
+                user.save()
+                return user
+        return False
+    
+    def create_inactive_user(self, username, password, email, send_email=True):
+        """
+        Creates a new User and a new RegistrationProfile for that
+        User, generates an activation key, and mails it.
+        
+        Pass ``send_email=False`` to disable sending the email.
+        
+        """
+        # Create the user.
+        new_user = User.objects.create_user(username, email, password)
+        new_user.is_active = False
+        new_user.save()
+        
+        # Generate a salted SHA1 hash to use as a key.
+        salt = sha.new(str(random.random())).hexdigest()[:5]
+        activation_key = sha.new(salt+new_user.username).hexdigest()
+        
+        # And finally create the profile.
+        new_profile = self.create(user=new_user,
+                                  activation_key=activation_key)
+        
+        if send_email:
+            from django.core.mail import send_mail
+            current_domain = Site.objects.get_current().domain
+            subject = "Activate your new account at %s" % current_domain
+            message_template = loader.get_template('registration/activation_email.txt')
+            message_context = Context({ 'site_url': 'http://%s/' % current_domain,
+                                        'activation_key': activation_key,
+                                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })
+            message = message_template.render(message_context)
+            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
+        return new_user
+    
+    def delete_expired_users(self):
+        """
+        Removes unused profiles and their associated accounts.
+
+        This is provided largely as a convenience for maintenance
+        purposes; if a RegistrationProfile's key expires without the
+        account being activated, then both the RegistrationProfile and
+        the associated User become clutter in the database, and (more
+        importantly) it won't be possible for anyone to ever come back
+        and claim the username. For best results, set this up to run
+        regularly as a cron job.
+        
+        If you have a User whose account you want to keep in the
+        database even though it's inactive (say, to prevent a
+        troublemaker from accessing or re-creating his account), just
+        delete that User's RegistrationProfile and this method will
+        leave it alone.
+        
+        """
+        for profile in self.all():
+            if profile.activation_key_expired():
+                user = profile.user
+                if not user.is_active:
+                    user.delete() # Removing the User will remove the RegistrationProfile, too.
+
+
+class RegistrationProfile(models.Model):
+    """
+    Simple profile model for a User, storing a registration date and
+    an activation key for the account.
+    
+    While it is possible to use this model as the value of the
+    ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
+    so. This model is intended solely to store some data needed for
+    user registration, and can do that regardless of what you set in
+    ``AUTH_PROFILE_MODULE``, so if you want to use user profiles in a
+    project, it's far better to develop a customized model for that
+    purpose and just let this one handle registration.
+    
+    """
+    user = models.ForeignKey(User, unique=True)
+    activation_key = models.CharField(maxlength=40)
+    key_generated = models.DateTimeField()
+    
+    objects = RegistrationManager()
+    
+    class Admin:
+        pass
+    
+    def save(self):
+        if not self.id:
+            self.key_generated = datetime.datetime.now()
+        super(RegistrationProfile, self).save()
+    
+    def __str__(self):
+        return "User profile for %s" % self.user.username
+    
+    def activation_key_expired(self):
+        """
+        Determines whether this Profile's activation key has expired,
+        based on the value of the setting ``ACCOUNT_ACTIVATION_DAYS``.
+        
+        """
+        expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
+        return self.key_generated + expiration_date <= datetime.datetime.now()

registration/templates/registration/activate.html

+{% extends "base.html" %}
+
+{% block title %}Account activation{% endblock %}
+{% block content_header %}Account activation{% endblock %}
+{% block main_content %}
+{% load humanize %}
+{% if account %}
+<p>Thanks for signing up! Now you can <a href="/accounts/login/">log in</a> and start contributing!</p>
+{% else %}
+<p>Either your activation link was incorrect, or the activation key for your account has expired; activation keys are only
+valid for {{ expiration_days|apnumber }} days after registration.</p>
+{% endif %}
+{% endblock %}

registration/templates/registration/activation_email.txt

+{% load humanize %}
+Someone, hopefully you, signed up for a new account at {{ site_url }} using this email address. If it was you, and you'd like to activate and use your account, click the link below or copy and paste it into your web browser's address bar:
+
+{{ site_url }}accounts/activate/{{ activation_key }}/
+
+If you didn't request this, you don't need to do anything; you won't receive any more email from us, and the account will expire automatically in {{ expiration_days|apnumber }} days.
+

registration/templates/registration/login.html

+{% extends "base.html" %}
+
+{% block title %}Log in{% endblock %}
+
+{% block content_header %}Log in{% endblock %}
+
+{% block main_content %}
+
+{% if form.errors %}
+<p class="error">Please correct the errors below:</p>
+{% endif %}
+
+<form method="post" action="{% if next %}?next={{ next }}{% endif %}">
+<dl>
+<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
+<dd>{{ form.username }}</dd>
+<dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt>
+<dd>{{ form.password }}</dd>
+<dt><input type="submit" value="Log in" /></dt>
+</dl>
+</form>
+{% endblock %}
+
+{% block sidebar %}
+<p>If you don't have an account, you can <a href="/accounts/register/">sign up</a> for one; it's free, and you'll get access to a bunch of nifty features.</p>
+{% endblock %}

registration/templates/registration/logout.html

+{% extends "base.html" %}
+
+{% block title %}Logged out{% endblock %}
+
+{% block content_header %}Logged out{% endblock %}
+
+{% block main_content %}
+<p>You've been logged out.</p>
+{% endblock %}
+
+{% block sidebar %}
+<p>Thanks for stopping by; when you come back, don't forget to <a href="/accounts/login/">log in</a> again.</p>
+{% endblock %}

registration/templates/registration/registration_complete.html

+{% extends "base.html" %}
+
+{% block title %}Registration complete{% endblock %}
+
+{% block content_header %}Registration complete{% endblock %}
+
+{% block main_content %}
+{% load humanize %}
+<p>An activation link has been sent to the email address you supplied, along with instructions for activating your account.</p>
+{% endblock %}

registration/templates/registration/registration_form.html

+{% extends "base.html" %}
+
+{% block title %}Sign up{% endblock %}
+
+{% block content_header %}Sign up{% endblock %}
+
+{% block main_content %}
+
+{% if form.errors %}
+<p class="error">Please correct the errors below:</p>
+{% endif %}
+
+<form method="post" action="">
+<dl>
+<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
+<dd>{{ form.username }}</dd>
+<dt><label for="id_email">Email address:</label>{% if form.email.errors %} <span class="error">{{ form.email.errors|join:", " }}</span>{% endif %}</dd>
+<dd>{{ form.email }}</dd>
+<dt><label for="id_password1">Password:</label>{% if form.password1.errors %} <span class="error">{{ form.password2.errors|join:", " }}</span>{% endif %}</dt>
+<dd>{{ form.password1 }}</dd>
+<dt><label for="id_password2">Password (type again to catch any typos):</label>{% if form.password2.errors %} <span class="error">{{ form.password2.errors|join:", " }}</span>{% endif %}</dt>
+<dd>{{ form.password2 }}</dd>
+<dt><label for="id_tos">I have read and agree to the <a href="/about/tos/">Terms of Service</a>:</label>{% if form.tos.errors %}&nbsp;<span class="error">{{ form.tos.errors|join:", " }}</span>{% endif %}&nbsp;&nbsp;{{ form.tos }}
+<dt><input type="submit" value="Register" /></dt>
+</dl>
+</form>
+{% endblock %}
+
+{% block sidebar %}
+<p>Fill out the form to the left (all fields are required), and your account will be created; you'll be sent an email with instructions on how to finish your registration.</p>
+{% endblock %}

registration/urls.py

+"""
+URLConf for Django user registration.
+
+Recommended usage is to use a call to ``include()`` in your project's
+root URLConf to include this URLConf for any URL begninning with
+'/accounts/'.
+
+"""
+
+from django.conf.urls.defaults import *
+from django.views.generic.simple import direct_to_template
+from django.contrib.auth.views import login, logout
+from views import activate, register
+
+urlpatterns = patterns('',
+                       # Activation keys get matched by \w+ instead of the more specific
+                       # [a-fA-F0-9]+ because a bad activation key should still get to the view;
+                       # that way it can return a sensible "invalid key" message instead of a
+                       # confusing 404.
+                       (r'^activate/(?P<activation_key>\w+)/$', activate),
+                       (r'^login/$', login, {'template_name': 'registration/login.html'}),
+                       (r'^logout/$', logout, {'template_name': 'registration/logout.html'}),
+                       (r'^register/$', register),
+                       (r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}),
+                       )

registration/views.py

+"""
+Views which allow users to create and activate accounts.
+
+"""
+
+from django.conf import settings
+from django.http import HttpResponseRedirect
+from django.shortcuts import render_to_response
+from django.template import RequestContext
+from models import RegistrationProfile
+from forms import RegistrationForm
+
+def activate(request, activation_key):
+    """
+    Activates a user's account, if their key is valid and hasn't
+    expired.
+
+    Context::
+        account
+            The ``User`` object corresponding to the account,
+            if the activation was successful.
+
+        expiration_days
+            The number of days for which activation keys stay valid.
+
+    Template::
+        registration/activate.html
+    
+    """
+    activation_key = activation_key.lower() # Normalize before trying anything with it.
+    account = RegistrationProfile.objects.activate_user(activation_key)
+    return render_to_response('registration/activate.html',
+                              {'account': account,
+                               'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
+                              context_instance=RequestContext(request))
+
+def register(request, success_url='/accounts/register/complete/'):
+    """
+    Allows a new user to register an account.
+
+    On successful registration, an email will be sent to the new user
+    with an activation link to click to make the account active. This
+    view will then redirect to ``success_url``, which defaults to
+    '/accounts/register/complete/'. This application has a URL pattern
+    for that URL and routes it to the ``direct_to_template`` generic
+    view to display a short message telling the user to check their
+    email for the account activation link.
+    
+    Context::
+        form
+            The registration form
+    
+    Template::
+        registration/registration_form.html
+    
+    """
+    if request.method == 'POST':
+        form = RegistrationForm(request.POST)
+        if form.is_valid():
+            new_user = RegistrationProfile.objects.create_inactive_user(username=form.cleaned_data['username'],
+                                                                        password=form.cleaned_data['password1'],
+                                                                        email=form.cleaned_data['email'])
+            return HttpResponseRedirect(success_url)
+    else:
+        form = RegistrationForm()
+    return render_to_response('registration/registration_form.html',
+                              { 'form': form },
+                              context_instance=RequestContext(request))

templates/registration/activate.html

-{% extends "base.html" %}
-
-{% block title %}Account activation{% endblock %}
-{% block content_header %}Account activation{% endblock %}
-{% block main_content %}
-{% load humanize %}
-{% if account %}
-<p>Thanks for signing up! Now you can <a href="/accounts/login/">log in</a> and start contributing!</p>
-{% else %}
-<p>Either your activation link was incorrect, or the activation key for your account has expired; activation keys are only
-valid for {{ expiration_days|apnumber }} days after registration.</p>
-{% endif %}
-{% endblock %}

templates/registration/activation_email.txt

-{% load humanize %}
-Someone, hopefully you, signed up for a new account at {{ site_url }} using this email address. If it was you, and you'd like to activate and use your account, click the link below or copy and paste it into your web browser's address bar:
-
-{{ site_url }}accounts/activate/{{ activation_key }}/
-
-If you didn't request this, you don't need to do anything; you won't receive any more email from us, and the account will expire automatically in {{ expiration_days|apnumber }} days.
-

templates/registration/login.html

-{% extends "base.html" %}
-
-{% block title %}Log in{% endblock %}
-
-{% block content_header %}Log in{% endblock %}
-
-{% block main_content %}
-
-{% if form.errors %}
-<p class="error">Please correct the errors below:</p>
-{% endif %}
-
-<form method="post" action="{% if next %}?next={{ next }}{% endif %}">
-<dl>
-<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
-<dd>{{ form.username }}</dd>
-<dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt>
-<dd>{{ form.password }}</dd>
-<dt><input type="submit" value="Log in" /></dt>
-</dl>
-</form>
-{% endblock %}
-
-{% block sidebar %}
-<p>If you don't have an account, you can <a href="/accounts/register/">sign up</a> for one; it's free, and you'll get access to a bunch of nifty features.</p>
-{% endblock %}

templates/registration/logout.html

-{% extends "base.html" %}
-
-{% block title %}Logged out{% endblock %}
-
-{% block content_header %}Logged out{% endblock %}
-
-{% block main_content %}
-<p>You've been logged out.</p>
-{% endblock %}
-
-{% block sidebar %}
-<p>Thanks for stopping by; when you come back, don't forget to <a href="/accounts/login/">log in</a> again.</p>
-{% endblock %}

templates/registration/registration_complete.html

-{% extends "base.html" %}
-
-{% block title %}Registration complete{% endblock %}
-
-{% block content_header %}Registration complete{% endblock %}
-
-{% block main_content %}
-{% load humanize %}
-<p>An activation link has been sent to the email address you supplied, along with instructions for activating your account.</p>
-{% endblock %}

templates/registration/registration_form.html

-{% extends "base.html" %}
-
-{% block title %}Sign up{% endblock %}
-
-{% block content_header %}Sign up{% endblock %}
-
-{% block main_content %}
-
-{% if form.errors %}
-<p class="error">Please correct the errors below:</p>
-{% endif %}
-
-<form method="post" action="">
-<dl>
-<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
-<dd>{{ form.username }}</dd>
-<dt><label for="id_email">Email address:</label>{% if form.email.errors %} <span class="error">{{ form.email.errors|join:", " }}</span>{% endif %}</dd>
-<dd>{{ form.email }}</dd>
-<dt><label for="id_password1">Password:</label>{% if form.password1.errors %} <span class="error">{{ form.password2.errors|join:", " }}</span>{% endif %}</dt>
-<dd>{{ form.password1 }}</dd>
-<dt><label for="id_password2">Password (type again to catch any typos):</label>{% if form.password2.errors %} <span class="error">{{ form.password2.errors|join:", " }}</span>{% endif %}</dt>
-<dd>{{ form.password2 }}</dd>
-<dt><label for="id_tos">I have read and agree to the <a href="/about/tos/">Terms of Service</a>:</label>{% if form.tos.errors %}&nbsp;<span class="error">{{ form.tos.errors|join:", " }}</span>{% endif %}&nbsp;&nbsp;{{ form.tos }}
-<dt><input type="submit" value="Register" /></dt>
-</dl>
-</form>
-{% endblock %}
-
-{% block sidebar %}
-<p>Fill out the form to the left (all fields are required), and your account will be created; you'll be sent an email with instructions on how to finish your registration.</p>
-{% endblock %}

urls.py

-"""
-URLConf for Django user registration.
-
-Recommended usage is to use a call to ``include()`` in your project's
-root URLConf to include this URLConf for any URL begninning with
-'/accounts/'.
-
-"""
-
-from django.conf.urls.defaults import *
-from django.views.generic.simple import direct_to_template
-from django.contrib.auth.views import login, logout
-from views import activate, register
-
-urlpatterns = patterns('',
-                       # Activation keys get matched by \w+ instead of the more specific
-                       # [a-fA-F0-9]+ because a bad activation key should still get to the view;
-                       # that way it can return a sensible "invalid key" message instead of a
-                       # confusing 404.
-                       (r'^activate/(?P<activation_key>\w+)/$', activate),
-                       (r'^login/$', login, {'template_name': 'registration/login.html'}),
-                       (r'^logout/$', logout, {'template_name': 'registration/logout.html'}),
-                       (r'^register/$', register),
-                       (r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}),
-                       )

views.py

-"""
-Views which allow users to create and activate accounts.
-
-"""
-
-from django.conf import settings
-from django.http import HttpResponseRedirect
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-from models import RegistrationProfile
-from forms import RegistrationForm
-
-def activate(request, activation_key):
-    """
-    Activates a user's account, if their key is valid and hasn't
-    expired.
-
-    Context::
-        account
-            The ``User`` object corresponding to the account,
-            if the activation was successful.
-
-        expiration_days
-            The number of days for which activation keys stay valid.
-
-    Template::
-        registration/activate.html
-    
-    """
-    activation_key = activation_key.lower() # Normalize before trying anything with it.
-    account = RegistrationProfile.objects.activate_user(activation_key)
-    return render_to_response('registration/activate.html',
-                              {'account': account,
-                               'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS },
-                              context_instance=RequestContext(request))
-
-def register(request, success_url='/accounts/register/complete/'):
-    """
-    Allows a new user to register an account.
-
-    On successful registration, an email will be sent to the new user
-    with an activation link to click to make the account active. This
-    view will then redirect to ``success_url``, which defaults to
-    '/accounts/register/complete/'. This application has a URL pattern
-    for that URL and routes it to the ``direct_to_template`` generic
-    view to display a short message telling the user to check their
-    email for the account activation link.
-    
-    Context::
-        form
-            The registration form
-    
-    Template::
-        registration/registration_form.html
-    
-    """
-    if request.method == 'POST':
-        form = RegistrationForm(request.POST)
-        if form.is_valid():
-            new_user = RegistrationProfile.objects.create_inactive_user(username=form.cleaned_data['username'],
-                                                                        password=form.cleaned_data['password1'],
-                                                                        email=form.cleaned_data['email'])
-            return HttpResponseRedirect(success_url)
-    else:
-        form = RegistrationForm()
-    return render_to_response('registration/registration_form.html',
-                              { 'form': form },
-                              context_instance=RequestContext(request))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.