Skip to content

Commit

Permalink
Working in django-registration. Some prep work for django-export scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
pydanny committed Aug 22, 2011
1 parent 8c55e7c commit 2bd7f5a
Show file tree
Hide file tree
Showing 16 changed files with 309 additions and 13 deletions.
Empty file added apps/accounts/__init__.py
Empty file.
94 changes: 94 additions & 0 deletions apps/accounts/backends.py
@@ -0,0 +1,94 @@
""" Your average django-registration backend """

from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site

from registration import signals
from registration.models import RegistrationProfile

from accounts.forms import RegistrationForm

from profiles.models import Profile

class DjangoPackagesRegistrationBackend(object):

def register(self, request, **kwargs):
"""
Assumes that the profiles copies the fields found in handstand.profiles.models.Profile
"""
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)

new_user = RegistrationProfile.objects.create_inactive_user(username, email,
password, site, send_email=settings.ACCOUNTS_ACTIVATION_EMAIL)

signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)

profile = Profile.objects.create(
user=new_user,
)
profile.save()

return new_user

def activate(self, request, activation_key):
"""
Given an an activation key, look up and activate the user
account corresponding to that key (if possible).
After successful activation, the signal
``registration.signals.user_activated`` will be sent, with the
newly activated ``User`` as the keyword argument ``user`` and
the class of this backend as the sender.
"""
activated = RegistrationProfile.objects.activate_user(activation_key)
if activated:
signals.user_activated.send(sender=self.__class__,
user=activated,
request=request)
return activated

def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)

def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm

def post_registration_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
user registration.
"""
return ('registration_complete', (), {})

def post_activation_redirect(self, request, user):
"""
Return the name of the URL to redirect to after successful
account activation.
"""
return ('registration_activation_complete', (), {})
72 changes: 72 additions & 0 deletions apps/accounts/forms.py
@@ -0,0 +1,72 @@
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _

from uni_form.helpers import FormHelper, Submit, Layout, Row

attrs_dict = {'class': 'required'}

class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
"""
username = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=30)),
label=_("User name"))

email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("Email address"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
label=_("Password (again)"))

helper = FormHelper()
layout = Layout(
'username',
'email',
Row('password1','password2'),
)

helper.add_layout(layout)

submit = Submit('register','Register')
helper.add_input(submit)

def clean(self):
"""
Verifiy that the values entered into the two password fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data

def clean_username(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(username__exact=self.cleaned_data['username']):
raise forms.ValidationError(_("This username is already in use. Please supply a different username."))
return self.cleaned_data['username']

def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return self.cleaned_data['email']
3 changes: 3 additions & 0 deletions apps/accounts/models.py
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
16 changes: 16 additions & 0 deletions apps/accounts/tests.py
@@ -0,0 +1,16 @@
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""

from django.test import TestCase


class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
35 changes: 35 additions & 0 deletions apps/accounts/urls.py
@@ -0,0 +1,35 @@
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import direct_to_template

from registration.views import activate
from registration.views import register

from accounts.forms import RegistrationForm


urlpatterns = patterns('',

url(r'^register/$',
register,
{'backend': "accounts.backends.DjangoPackagesRegistrationBackend",
'form_class': RegistrationForm},
name='registration_register'),
url(r'^activate/complete/$',
direct_to_template,
{'template': 'registration/activation_complete.html'},
name='registration_activation_complete'),
url(r'^activate/(?P<activation_key>\w+)/$',
activate,
{'backend': "accounts.backends.StockRegistrationBackend"},
name='registration_activate'),
url(r'^register/complete/$',
direct_to_template,
{'template': 'registration/registration_complete.html'},
name='registration_complete'),
url(r'^register/closed/$',
direct_to_template,
{'template': 'registration/registration_closed.html'},
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
1 change: 1 addition & 0 deletions apps/accounts/views.py
@@ -0,0 +1 @@
# Create your views here.
2 changes: 1 addition & 1 deletion apps/homepage/context_processors.py
Expand Up @@ -26,6 +26,6 @@ def current_path(request):
"""
context = {}
if request.path not in (reverse('logout'), reverse('acct_signup')):
if request.path not in (reverse('logout'), reverse('registration_register')):
context['current_path'] = request.path
return context
7 changes: 6 additions & 1 deletion apps/profiles/context_processors.py
@@ -1,3 +1,4 @@
from django.conf import settings
from django.utils.functional import lazy, memoize, SimpleLazyObject

def lazy_profile(request):
Expand All @@ -12,4 +13,8 @@ def get_user_profile():
else:
return request.user.get_profile()

return {'profile': SimpleLazyObject(get_user_profile)}
data = {
'profile': SimpleLazyObject(get_user_profile),
'ACCOUNT_OPEN_SIGNUP': settings.ACCOUNT_OPEN_SIGNUP, # TODO - put this into the request some other, better way
}
return data
13 changes: 12 additions & 1 deletion requirements/mkii.txt
Expand Up @@ -12,6 +12,7 @@ django-uni-form==0.7.0
django-pagination==1.0.7
django-notification==0.1.4


django_extensions==0.4.1
simplejson==2.1.1
github2==0.2.0
Expand All @@ -30,4 +31,14 @@ django-classy-tags==0.3.3.1
celery==2.2.4
kombu==1.0.4
django-celery==2.2.4
django-kombu==0.9.2
django-kombu==0.9.2

# django modeler work
django-modeler==0.1

# Open ID
python-openid==2.2.5
django-social-auth==0.5.6

# WARNING: you may need to update this
-e hg+https://bitbucket.org/ubernostrum/django-registration/#egg=django-registration
6 changes: 6 additions & 0 deletions settings.py
Expand Up @@ -162,6 +162,7 @@
"reversion",
"django_sorting",
"flatblocks",
"registration",

# Celery task queue:
'djcelery',
Expand Down Expand Up @@ -270,6 +271,11 @@
LOCAL_INSTALLED_APPS = []
SUPPORTED_REPO = []

# accounts settings
ACCOUNTS_ACTIVATION_EMAIL = True
if DEBUG:
ACCOUNTS_ACTIVATION_EMAIL = False

# local_settings.py can be used to override environment-specific settings
# like database and email that differ between development and production.
try:
Expand Down
3 changes: 1 addition & 2 deletions templates/about/what_next.html
Expand Up @@ -30,8 +30,7 @@ <h1>{% trans "What Next?" %}</h1>

<p class="what_next">
{% ifsetting ACCOUNT_OPEN_SIGNUP %}
{% url acct_signup as signup_url %}
{% blocktrans %}Start by <a href="{{ signup_url }}">signing up</a> and <a href="{{ login_url }}">logging in</a>.{% endblocktrans %}
{% blocktrans %}Start by <a href="{% url registration_register %}">signing up</a> and <a href="{{ login_url }}">logging in</a>.{% endblocktrans %}
{% else %}
{% blocktrans %}Start by <a href="{{ login_url }}">logging in</a>.{% endblocktrans %}
{% endifsetting %}
Expand Down
10 changes: 4 additions & 6 deletions templates/account/login.html
Expand Up @@ -21,13 +21,11 @@
<h1>{% trans "Log In" %}</h1>

{% if user.is_authenticated %}
{% user_display user as user_display %}
<p><span class="warning">{% trans "Note" %}</span>: {% blocktrans %}you are already logged in as {{ user_display }}.{% endblocktrans %}</p>
<p><span class="warning">{% trans "Note" %}</span>: {% blocktrans %}you are already logged in as {{ request.user }}.{% endblocktrans %}</p>
{% else %}
{% ifsetting ACCOUNT_OPEN_SIGNUP %}
{% url acct_signup as signup_url %}
<p>{% blocktrans %}Don't have an account? <a class="sign_up" href="{{ signup_url }}">Sign up</a>!{% endblocktrans %}</p>
{% endifsetting %}
{% if request.ACCOUNT_OPEN_SIGNUP %}
<p>Don't have an account? <a class="sign_up" href="{% url registration_register %}">Sign up</a>!</p>
{% endif %}
{% endif %}

<form class="login uniForm" method="POST" action="{% url login %}">
Expand Down
2 changes: 1 addition & 1 deletion templates/account/signup.html
Expand Up @@ -19,7 +19,7 @@ <h1>{% trans "Sign Up" %}</h1>
{% else %}
<p>{% trans "Already have an account?" %} <a class="sign_up" href="{% url login %}">{% trans "Log In" %}</a>!</p>

<form class="signup uniForm" id="signup_form" method="post" action="{% url acct_signup %}">
<form class="signup uniForm" id="signup_form" method="post" action="{% url registration_register %}">
{% csrf_token %}
<fieldset class="inlineLabels">
{{ form|as_uni_form }}
Expand Down
2 changes: 1 addition & 1 deletion templates/base.html
Expand Up @@ -71,7 +71,7 @@
{% else %}
<a href="/help/">{% trans "Help" %}</a>
|
<a href="{% url login %}{% if current_path %}?next={{ current_path }}{% endif %}">{% trans "Log in" %}</a> {% trans "or" %} <a href="{% url acct_signup %}">{% trans "Sign Up" %}</a>
<a href="{% url login %}{% if current_path %}?next={{ current_path }}{% endif %}">{% trans "Log in" %}</a> {% trans "or" %} <a href="{% url registration_register %}">{% trans "Sign Up" %}</a>
<br/>
{% endif %}
{% block locale_switcher %}{% endblock %}
Expand Down

0 comments on commit 2bd7f5a

Please sign in to comment.