Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Released version 0.4 of django-userprofiles.

* Added more tests
* Fixed datetime/timezone errors
* Refactored views to use class based views
* Added explicit setting to enable emailverifications

Merge branch 'release/0.4'
  • Loading branch information...
commit 79227566abe53ee9b834709b35ae276b40114c0b 2 parents 3e86ffb + f59f49b
@stephrdev authored
Showing with 968 additions and 421 deletions.
  1. +14 −0 .travis.yml
  2. +1 −0  AUTHORS
  3. +4 −0 Makefile
  4. +7 −1 README.rst
  5. +0 −11 example_project/manage.py
  6. +0 −51 example_project/settings.py
  7. +0 −9 example_project/urls.py
  8. +2 −2 setup.py
  9. 0  {example_project/accounts → test_project}/__init__.py
  10. +10 −0 test_project/manage.py
  11. +3 −0  test_project/requirements.txt
  12. +35 −0 test_project/settings.py
  13. +0 −1  {example_project → test_project}/templates/base.html
  14. 0  {example_project → test_project/test_accounts}/__init__.py
  15. +2 −2 {example_project/accounts → test_project/test_accounts}/forms.py
  16. +1 −1  {example_project/accounts → test_project/test_accounts}/models.py
  17. +6 −0 test_project/urls.py
  18. +3 −4 userprofiles/admin.py
  19. +0 −1  userprofiles/auth_backends.py
  20. +8 −6 userprofiles/contrib/accountverification/models.py
  21. 0  userprofiles/contrib/accountverification/tests/__init__.py
  22. +61 −0 userprofiles/contrib/accountverification/tests/test_models.py
  23. +40 −0 userprofiles/contrib/accountverification/tests/test_views.py
  24. +1 −1  userprofiles/contrib/accountverification/urls.py
  25. +14 −9 userprofiles/contrib/accountverification/views.py
  26. +2 −5 userprofiles/contrib/emailverification/forms.py
  27. +5 −3 userprofiles/contrib/emailverification/models.py
  28. 0  userprofiles/contrib/emailverification/tests/__init__.py
  29. +89 −0 userprofiles/contrib/emailverification/tests/test_views.py
  30. +1 −1  userprofiles/contrib/emailverification/urls.py
  31. +41 −30 userprofiles/contrib/emailverification/views.py
  32. +1 −1  userprofiles/contrib/profiles/forms.py
  33. 0  userprofiles/contrib/profiles/tests/__init__.py
  34. +91 −0 userprofiles/contrib/profiles/tests/test_views.py
  35. +1 −1  userprofiles/contrib/profiles/urls.py
  36. +33 −28 userprofiles/contrib/profiles/views.py
  37. +8 −10 userprofiles/forms.py
  38. BIN  userprofiles/locale/de/LC_MESSAGES/django.mo
  39. +61 −53 userprofiles/locale/de/LC_MESSAGES/django.po
  40. +11 −0 userprofiles/mixins.py
  41. +58 −68 userprofiles/settings.py
  42. +3 −2 userprofiles/templates/userprofiles/login.html
  43. +1 −1  userprofiles/templates/userprofiles/mails/activation_email.html
  44. +1 −1  userprofiles/templates/userprofiles/mails/emailverification.html
  45. +1 −1  userprofiles/templates/userprofiles/mails/password_reset_email.html
  46. +0 −2  userprofiles/tests/__init__.py
  47. +0 −37 userprofiles/tests/forms.py
  48. +0 −23 userprofiles/tests/runtests.py
  49. +35 −0 userprofiles/tests/test_auth_backends.py
  50. +187 −0 userprofiles/tests/test_forms.py
  51. +41 −0 userprofiles/tests/test_settings.py
  52. +38 −0 userprofiles/tests/test_utils.py
  53. +12 −19 userprofiles/tests/{views.py → test_views.py}
  54. +1 −2  userprofiles/urls.py
  55. +6 −5 userprofiles/utils.py
  56. +28 −29 userprofiles/views.py
View
14 .travis.yml
@@ -0,0 +1,14 @@
+language: python
+python:
+ - "2.6"
+ - "2.7"
+env:
+ - DJANGO=1.4.5
+ - DJANGO=1.5
+install:
+ - pip install -q Django==$DJANGO --use-mirrors
+ - pip install -q -r test_project/requirements.txt --use-mirrors
+ - pip install -q -e . --use-mirrors
+
+script:
+ - make test
View
1  AUTHORS
@@ -1,5 +1,6 @@
* Stephan Jaekel <steph@rdev.info>
* Frank Wiles <frank@revsys.com>
+* Peter Heise <info@pheise-it.de>
Translations:
View
4 Makefile
@@ -0,0 +1,4 @@
+test:
+ flake8 userprofiles --ignore=E501,E128
+ coverage run --branch --source=userprofiles `which django-admin.py` test --settings=test_project.settings userprofiles
+ coverage report --show-missing --omit=*test*
View
8 README.rst
@@ -30,7 +30,7 @@ Registration settings
This app provides a mechanism to verify user accounts by sending an email
with an activation link. To use the account verification you have to add
`userprofiles.contrib.accountverification` to your `INSTALLED_APPS` in
- order toto enable the verification.
+ order to enable the verification.
`USERPROFILES_ACCOUNT_VERIFICATION_DAYS`
Defines the amount of days a user has to activate his account. Defaults to
@@ -93,6 +93,12 @@ userprofiles.contrib.emailverification
django-userprofiles provides a simple app to do confirmed email address changes.
(Users have the re-verify their email address after a change)
+`USERPROFILES_USE_EMAIL_VERIFICATION`
+ This app provides a mechanism to verify email changes by sending an email
+ with an activation link. To use the email verification you have to add
+ `userprofiles.contrib.emailverification` to your `INSTALLED_APPS` in
+ order to enable the verification.
+
`USERPROFILES_EMAIL_VERIFICATION_DAYS`
Defines the number of days a user has time to verify her/his new email
address. Defaults to 2.
View
11 example_project/manage.py
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-from django.core.management import execute_manager
-try:
- import settings # Assumed to be in the same directory.
-except ImportError:
- import sys
- sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
- sys.exit(1)
-
-if __name__ == "__main__":
- execute_manager(settings)
View
51 example_project/settings.py
@@ -1,51 +0,0 @@
-import os
-
-PROJECT_ROOT = os.path.dirname(__file__)
-
-DEBUG = True
-
-DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'local_database.db',
- 'TEST_NAME': ':memory:',
- }
-}
-
-SITE_ID = 1
-
-SECRET_KEY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
-
-ROOT_URLCONF = 'example_project.urls'
-
-TEMPLATE_DIRS = (
- os.path.join(PROJECT_ROOT, 'templates'),
-)
-
-INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'django.contrib.admin',
- 'userprofiles',
- #'userprofiles.contrib.accountverification',
- #'userprofiles.contrib.emailverification',
- #'userprofiles.contrib.profiles',
- #'accounts',
-)
-
-EMAIL_HOST = 'localhost'
-EMAIL_PORT = '2525'
-
-#AUTH_PROFILE_MODULE = 'accounts.Profile'
-
-#USERPROFILES_CHECK_UNIQUE_EMAIL = True
-#USERPROFILES_DOUBLE_CHECK_EMAIL = True
-#USERPROFILES_DOUBLE_CHECK_PASSWORD = True
-#USERPROFILES_REGISTRATION_FULLNAME = True
-#USERPROFILES_USE_ACCOUNT_VERIFICATION = True
-#USERPROFILES_REGISTRATION_FORM = 'accounts.forms.ProfileRegistrationForm'
-#USERPROFILES_USE_PROFILE = True
-#USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE = True
-#USERPROFILES_INLINE_PROFILE_ADMIN = True
View
9 example_project/urls.py
@@ -1,9 +0,0 @@
-from django.conf.urls.defaults import *
-
-from django.contrib import admin
-admin.autodiscover()
-
-urlpatterns = patterns('',
- (r'^admin/', include(admin.site.urls)),
- (r'^accounts/', include('userprofiles.urls')),
-)
View
4 setup.py
@@ -6,13 +6,13 @@ def read(fname):
setup(
name='django-userprofiles',
- version='0.3.1',
+ version='0.4',
description='Registration, e-mail verifications and profiles.',
long_description=read('README.rst'),
author='Stephan Jaekel',
author_email='steph@rdev.info',
url='https://github.com/stephrdev/django-userprofiles/',
- packages=find_packages(exclude=['example_project', 'example_project.*']),
+ packages=find_packages(exclude=['test_project', 'test_project.*']),
package_data = {
'userprofiles': ['templates/userprofiles/*.html', 'templates/userprofiles/*/*.html',
'locale/de/LC_MESSAGES/*'],
View
0  example_project/accounts/__init__.py → test_project/__init__.py
File renamed without changes
View
10 test_project/manage.py
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+import os
+import sys
+
+if __name__ == "__main__":
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")
+
+ from django.core.management import execute_from_command_line
+
+ execute_from_command_line(sys.argv)
View
3  test_project/requirements.txt
@@ -0,0 +1,3 @@
+django-discover-runner
+flake8
+coverage
View
35 test_project/settings.py
@@ -0,0 +1,35 @@
+import os
+
+TEST_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
+ '..', 'userprofiles', 'tests'))
+
+TEST_RUNNER = 'discover_runner.DiscoverRunner'
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': ':memory:',
+ }
+}
+
+INSTALLED_APPS = [
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'userprofiles',
+ 'userprofiles.contrib.accountverification',
+ 'userprofiles.contrib.emailverification',
+ 'userprofiles.contrib.profiles',
+ 'test_project.test_accounts',
+]
+
+TEMPLATE_DIRS = (
+ os.path.join(os.path.dirname(__file__), 'templates'),
+)
+
+ROOT_URLCONF = 'test_project.urls'
+
+SITE_ID = 1
+
+SECRET_KEY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
View
1  example_project/templates/base.html → test_project/templates/base.html
@@ -1,7 +1,6 @@
<!DOCTYPE html>
<html>
<head>
- <title>{% block title %}example project...{% endblock %}</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
View
0  example_project/__init__.py → test_project/test_accounts/__init__.py
File renamed without changes
View
4 example_project/accounts/forms.py → test_project/test_accounts/forms.py
@@ -1,8 +1,9 @@
from django import forms
-from accounts.models import Profile
+from .models import Profile
from userprofiles.forms import RegistrationForm
+
class ProfileRegistrationForm(RegistrationForm):
short_info = forms.CharField(widget=forms.Textarea)
@@ -11,4 +12,3 @@ def save_profile(self, new_user, *args, **kwargs):
user=new_user,
short_info=self.cleaned_data['short_info']
)
-
View
2  example_project/accounts/models.py → test_project/test_accounts/models.py
@@ -1,8 +1,8 @@
from django.db import models
from django.contrib.auth.models import User
+
class Profile(models.Model):
user = models.OneToOneField(User)
short_info = models.TextField(blank=True)
-
View
6 test_project/urls.py
@@ -0,0 +1,6 @@
+from django.conf.urls import patterns, include
+
+
+urlpatterns = patterns('',
+ (r'^userprofiles/', include('userprofiles.urls')),
+)
View
7 userprofiles/admin.py
@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
from django.contrib import admin
-
-from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
+from django.contrib.auth.models import User
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
if up_settings.USE_PROFILE and up_settings.INLINE_PROFILE_ADMIN:
@@ -18,6 +17,6 @@ class UserProfileInline(admin.StackedInline):
max_num = 1
class UserProfileAdmin(UserAdmin):
- inlines = [UserProfileInline,]
+ inlines = [UserProfileInline]
admin.site.register(User, UserProfileAdmin)
View
1  userprofiles/auth_backends.py
@@ -15,4 +15,3 @@ def authenticate(self, username=None, password=None):
return user
except User.DoesNotExist:
return None
-
View
14 userprofiles/contrib/accountverification/models.py
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
-from datetime import datetime, timedelta
+from datetime import timedelta
+import hashlib
import random
import re
import uuid
@@ -10,10 +11,10 @@
from django.core.mail import send_mail
from django.db import models
from django.template.loader import render_to_string
-from django.utils.hashcompat import sha_constructor
from django.utils.translation import gettext_lazy as _
+from django.utils import timezone
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
SHA1_RE = re.compile('^[a-f0-9]{40}$')
@@ -60,8 +61,8 @@ def create_inactive_user(self, username, password, email):
return new_user
def create_verification(self, user):
- salt = sha_constructor(str(random.random())).hexdigest()[:5]
- activation_key = sha_constructor(salt + str(uuid.uuid4())).hexdigest()
+ salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
+ activation_key = hashlib.sha1(salt + str(uuid.uuid4())).hexdigest()
return self.create(user=user, activation_key=activation_key)
def delete_expired_users(self):
@@ -71,6 +72,7 @@ def delete_expired_users(self):
if not user.is_active:
user.delete()
+
class AccountVerification(models.Model):
ACTIVATED = 'ALREADY_ACTIVATED'
@@ -85,7 +87,7 @@ def __unicode__(self):
def activation_key_expired(self):
expiration_date = timedelta(days=up_settings.ACCOUNT_VERIFICATION_DAYS)
return (self.activation_key == self.ACTIVATED
- or (self.user.date_joined + expiration_date <= datetime.now()))
+ or (self.user.date_joined + expiration_date <= timezone.now()))
activation_key_expired.boolean = True
class Meta:
View
0  userprofiles/contrib/accountverification/tests/__init__.py
No changes.
View
61 userprofiles/contrib/accountverification/tests/test_models.py
@@ -0,0 +1,61 @@
+from datetime import timedelta
+
+from django.contrib.auth.models import User
+from django.test import TestCase
+
+from userprofiles.contrib.accountverification.models import AccountVerification
+from userprofiles.settings import up_settings
+
+
+class ModelsTests(TestCase):
+ def setUp(self):
+ self.data = {
+ 'username': 'newuser',
+ 'email': 'newuser@example.com',
+ 'password': 'newuserpass',
+ }
+
+ def test_activate_user(self):
+ user = AccountVerification.objects.create_inactive_user(
+ self.data['username'], self.data['password'], self.data['email'])
+ user.date_joined = user.date_joined - timedelta(
+ days=up_settings.ACCOUNT_VERIFICATION_DAYS, seconds=1)
+ user.save()
+
+ verification = AccountVerification.objects.get(user=user)
+
+ self.assertFalse(
+ AccountVerification.objects.activate_user('wrong-pattern-format'))
+
+ self.assertFalse(
+ AccountVerification.objects.activate_user('f4a80274f851cb41ef9c20d00426d72fc4874471'))
+
+ self.assertFalse(
+ AccountVerification.objects.activate_user(verification.activation_key))
+
+ def test_delete_expired_users(self):
+ user = AccountVerification.objects.create_inactive_user(
+ self.data['username'], self.data['password'], self.data['email'])
+
+ # Test with inactive user, but not expired
+ AccountVerification.objects.delete_expired_users()
+ self.assertTrue(User.objects.filter(pk=user.pk).exists())
+
+ # Test with active and not expired user
+ user.is_active = True
+ user.save()
+ AccountVerification.objects.delete_expired_users()
+ self.assertTrue(User.objects.filter(pk=user.pk).exists())
+
+ # Test with active but expired user
+ user.date_joined = user.date_joined - timedelta(
+ days=up_settings.ACCOUNT_VERIFICATION_DAYS + 1)
+ user.save()
+ AccountVerification.objects.delete_expired_users()
+ self.assertTrue(User.objects.filter(pk=user.pk).exists())
+
+ # Test with expired and inactive user
+ user.is_active = False
+ user.save()
+ AccountVerification.objects.delete_expired_users()
+ self.assertFalse(User.objects.filter(pk=user.pk).exists())
View
40 userprofiles/contrib/accountverification/tests/test_views.py
@@ -0,0 +1,40 @@
+import re
+
+from django.core import mail
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from userprofiles.contrib.accountverification.models import AccountVerification
+
+
+@override_settings(USE_ACCOUNT_VERIFICATION=True)
+class ViewTests(TestCase):
+ def setUp(self):
+ self.data = {
+ 'username': 'newuser',
+ 'email': 'newuser@example.com',
+ 'password': 'newuserpass',
+ }
+
+ def test_registration_activate(self):
+ AccountVerification.objects.create_inactive_user(
+ self.data['username'], self.data['password'], self.data['email'])
+
+ self.assertEqual(len(mail.outbox), 1)
+
+ activation_key_match = re.findall(
+ r'http://example.com/userprofiles/activate/(\w+)',
+ mail.outbox[0].body, re.MULTILINE)
+
+ self.assertEqual(len(activation_key_match), 1)
+
+ activation_key = activation_key_match[0]
+
+ url = reverse('userprofiles_registration_activate',
+ kwargs={'activation_key': activation_key})
+
+ response = self.client.get(url)
+ self.assertTrue(
+ 'We activated your account. You are now able to log in. Have fun!' in
+ response.content)
View
2  userprofiles/contrib/accountverification/urls.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from django.conf.urls.defaults import patterns, url
+from django.conf.urls import patterns, url
urlpatterns = patterns('userprofiles.contrib.accountverification.views',
View
23 userprofiles/contrib/accountverification/views.py
@@ -1,15 +1,20 @@
# -*- coding: utf-8 -*-
-from django.shortcuts import render
+from django.views.generic import TemplateView
-from userprofiles import settings as up_settings
from userprofiles.contrib.accountverification.models import AccountVerification
+from userprofiles.settings import up_settings
-def registration_activate(request, activation_key):
- activation_key = activation_key.lower()
- account = AccountVerification.objects.activate_user(activation_key)
+class RegistrationActivateView(TemplateView):
+ template_name = 'userprofiles/registration_activate.html'
- return render(request, 'userprofiles/registration_activate.html', {
- 'account': account,
- 'expiration_days': up_settings.ACCOUNT_VERIFICATION_DAYS
- })
+ def get_context_data(self, **kwargs):
+ activation_key = kwargs['activation_key'].lower()
+ account = AccountVerification.objects.activate_user(activation_key)
+
+ return {
+ 'account': account,
+ 'expiration_days': up_settings.ACCOUNT_VERIFICATION_DAYS
+ }
+
+registration_activate = RegistrationActivateView.as_view()
View
7 userprofiles/contrib/emailverification/forms.py
@@ -25,10 +25,7 @@ def clean_new_email(self):
return new_email
- def save(self, user=None):
- if not user:
- return None
-
+ def save(self, user):
verification = EmailVerification.objects.create(user=user,
old_email=user.email, new_email=self.cleaned_data['new_email'])
@@ -43,6 +40,6 @@ def save(self, user=None):
body = render_to_string('userprofiles/mails/emailverification.html', context)
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL,
- [self.cleaned_data['new_email'],])
+ [self.cleaned_data['new_email']])
return verification
View
8 userprofiles/contrib/emailverification/models.py
@@ -1,19 +1,21 @@
# -*- coding: utf-8 -*-
-from datetime import datetime, timedelta
+from datetime import timedelta
import uuid
from django.contrib.auth.models import User
from django.db import models
+from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
def generate_token():
return str(uuid.uuid4())
+
def generate_confirm_expire_date():
- return datetime.now() + timedelta(days=up_settings.EMAIL_VERIFICATION_DAYS)
+ return timezone.now() + timedelta(days=up_settings.EMAIL_VERIFICATION_DAYS)
class EmailVerification(models.Model):
View
0  userprofiles/contrib/emailverification/tests/__init__.py
No changes.
View
89 userprofiles/contrib/emailverification/tests/test_views.py
@@ -0,0 +1,89 @@
+from django.contrib.auth.models import User
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from userprofiles.contrib.emailverification.models import EmailVerification
+from userprofiles.settings import up_settings
+
+
+@override_settings(USERPROFILES_USE_PROFILE=False, USERPROFILES_USE_EMAIL_VERIFICATION=True)
+class ViewTests(TestCase):
+
+ def setUp(self):
+ self.data = {
+ 'username': 'newuser',
+ 'email': 'newuser@example.com',
+ 'email_repeat': 'newuser@example.com',
+ 'password': 'newuserpass',
+ 'password_repeat': 'newuserpass',
+ 'first_name': 'New',
+ 'last_name': 'User',
+ }
+
+ self.user = User.objects.create_user(self.data['username'],
+ self.data['email'], self.data['password'])
+
+ def tearDown(self):
+ self.user.delete()
+
+ def test_email_change(self):
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ response = self.client.get(reverse('userprofiles_email_change'))
+
+ response = self.client.post(reverse('userprofiles_email_change'),
+ {'new_email': 'test@example.com'}, follow=True)
+
+ self.assertTrue(EmailVerification.objects.filter(user=self.user).exists())
+
+ self.assertEqual(response.context['expiration_days'], up_settings.EMAIL_VERIFICATION_DAYS)
+
+ def test_email_change_email_in_use(self):
+ EmailVerification.objects.create(
+ user=self.user, old_email=self.user.email, new_email='test@example.com')
+
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ response = self.client.post(reverse('userprofiles_email_change'),
+ {'new_email': 'test@example.com'}, follow=True)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertFormError(response, 'form', 'new_email',
+ [u'This email address is already in use. Please supply a different email address.'])
+
+ def test_email_change_approve(self):
+ verification = EmailVerification.objects.create(
+ user=self.user, old_email=self.user.email, new_email='test@example.com')
+
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ url = reverse('userprofiles_email_change_approve',
+ kwargs={'token': verification.token, 'code': verification.code})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(User.objects.get(pk=self.user.pk).email, 'test@example.com')
+
+ self.assertFalse(EmailVerification.objects.filter(user=self.user,
+ is_approved=False).exists())
+
+ def test_email_change_approve_not_exists(self):
+ verification = EmailVerification.objects.create(
+ user=self.user, old_email=self.user.email, new_email='test@example.com')
+
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ url = reverse('userprofiles_email_change_approve',
+ kwargs={'token': verification.token, 'code': 'wrong-code'})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(User.objects.get(pk=self.user.pk).email, self.user.email)
+
+ url = reverse('userprofiles_email_change_approve',
+ kwargs={'token': 'wrong-token', 'code': verification.code})
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(User.objects.get(pk=self.user.pk).email, self.user.email)
View
2  userprofiles/contrib/emailverification/urls.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from django.conf.urls.defaults import patterns, url
+from django.conf.urls import patterns, url
urlpatterns = patterns('userprofiles.contrib.emailverification.views',
View
71 userprofiles/contrib/emailverification/views.py
@@ -1,45 +1,56 @@
# -*- coding: utf-8 -*-
from django.contrib import messages
-from django.contrib.auth.decorators import login_required
-from django.shortcuts import render, redirect
+from django.core.urlresolvers import reverse
+from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
+from django.views.generic import FormView, TemplateView, RedirectView
-from userprofiles import settings as up_settings
from userprofiles.contrib.emailverification.forms import ChangeEmailForm
from userprofiles.contrib.emailverification.models import EmailVerification
+from userprofiles.mixins import LoginRequiredMixin
+from userprofiles.settings import up_settings
-@login_required
-def email_change(request):
- if request.method == 'POST':
- form = ChangeEmailForm(request.POST)
- if form.is_valid():
- verification = form.save(request.user)
- return redirect('userprofiles_email_change_requested')
- else:
- form = ChangeEmailForm()
+class EmailChangeView(LoginRequiredMixin, FormView):
+ template_name = 'userprofiles/email_change.html'
+ form_class = ChangeEmailForm
- return render(request, 'userprofiles/email_change.html', {'form': form})
+ def form_valid(self, form):
+ form.save(self.request.user)
+ return redirect('userprofiles_email_change_requested')
+email_change = EmailChangeView.as_view()
-@login_required
-def email_change_requested(request):
- return render(request, 'userprofiles/email_change_requested.html', {
- 'expiration_days': up_settings.EMAIL_VERIFICATION_DAYS})
+class EmailChangeRequestedView(LoginRequiredMixin, TemplateView):
+ template_name = 'userprofiles/email_change_requested.html'
-@login_required
-def email_change_approve(request, token, code):
- try:
- verification = EmailVerification.objects.get(token=token, code=code,
- user=request.user, is_expired=False, is_approved=False)
+ def get_context_data(self, **kwargs):
+ return {
+ 'expiration_days': up_settings.EMAIL_VERIFICATION_DAYS
+ }
- verification.is_approved = True
- verification.save()
- messages.success(request, _(u'E-mail address changed to %(email)s' % {
- 'email': verification.new_email}))
- except EmailVerification.DoesNotExist:
- messages.error(request,
- _(u'Unable to change e-mail address. Confirmation link is invalid.'))
+email_change_requested = EmailChangeRequestedView.as_view()
- return redirect(up_settings.EMAIL_VERIFICATION_DONE_URL)
+
+class EmailChangeApproveView(LoginRequiredMixin, RedirectView):
+ permanent = False
+
+ def get_redirect_url(self, token, code):
+ try:
+ verification = EmailVerification.objects.get(token=token, code=code,
+ user=self.request.user, is_expired=False, is_approved=False)
+
+ verification.is_approved = True
+ verification.save()
+
+ messages.success(self.request, _(u'E-mail address changed to %(email)s' % {
+ 'email': verification.new_email}))
+
+ except EmailVerification.DoesNotExist:
+ messages.error(self.request,
+ _(u'Unable to change e-mail address. Confirmation link is invalid.'))
+
+ return reverse(up_settings.EMAIL_VERIFICATION_DONE_URL)
+
+email_change_approve = EmailChangeApproveView.as_view()
View
2  userprofiles/contrib/profiles/forms.py
@@ -2,7 +2,7 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
from userprofiles.utils import UserProfile
View
0  userprofiles/contrib/profiles/tests/__init__.py
No changes.
View
91 userprofiles/contrib/profiles/tests/test_views.py
@@ -0,0 +1,91 @@
+from django.contrib.auth.models import User
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from test_project.test_accounts.models import Profile
+
+
+@override_settings(USERPROFILES_USE_PROFILE=True, AUTH_PROFILE_MODULE='test_accounts.Profile')
+class ViewTests(TestCase):
+ def setUp(self):
+ self.data = {
+ 'username': 'newuser',
+ 'email': 'newuser@example.com',
+ 'new_email': 'anotheremail@example.com',
+ 'password': 'newuserpass',
+ 'first_name': 'John',
+ 'last_name': 'Doe',
+ 'short_info': 'Short Info Test!'
+ }
+ self.user = User.objects.create_user(self.data['username'], self.data['email'],
+ self.data['password'])
+ Profile(user=self.user).save()
+
+ def tearDown(self):
+ User.objects.get(username=self.data['username']).delete()
+
+ def test_profile_view(self):
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ url = reverse('userprofiles_profile')
+ response = self.client.get(url)
+
+ self.assertEqual(response.context['user'], self.user)
+
+ @override_settings(USERPROFILES_REGISTRATION_FULLNAME=True)
+ def test_profile_change_fullname_enabled(self):
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ change_url = reverse('userprofiles_profile_change')
+
+ response = self.client.get(change_url)
+ self.assertTrue('first_name' in response.context['form'].fields and
+ 'last_name' in response.context['form'].fields)
+
+ self.client.post(change_url, {'first_name': self.data['first_name'],
+ 'last_name': self.data['last_name']})
+ response = self.client.get(change_url)
+
+ self.assertTrue(User.objects.filter(pk=self.user.pk,
+ first_name=self.data['first_name'], last_name=self.data['last_name']).exists())
+
+ def test_profile_change_fullname_disabled(self):
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ change_url = reverse('userprofiles_profile_change')
+
+ response = self.client.get(change_url)
+ self.assertFalse('first_name' in response.context['form'].fields and
+ 'last_name' in response.context['form'].fields)
+
+ @override_settings(USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE=True)
+ def test_profile_change_email_enabled(self):
+ self.client.login(username=self.data['username'], password=self.data['password'])
+
+ change_url = reverse('userprofiles_profile_change')
+
+ response = self.client.get(change_url)
+ self.assertTrue('email' in response.context['form'].fields)
+
+ self.client.post(change_url, {'email': self.data['new_email']})
+ response = self.client.get(change_url)
+
+ self.assertTrue(User.objects.filter(pk=self.user.pk,
+ email=self.data['new_email']).exists())
+
+# def test_profile_change_test_extra_fields(self):
+# self.assertEqual(self.user.profile.short_info, '')
+#
+# self.client.login(username=self.data['username'], password=self.data['password'])
+#
+# change_url = reverse('userprofiles_profile_change')
+#
+# response = self.client.get(change_url)
+#
+# self.assertTrue('short_info' in response.context['form'].fields)
+#
+# self.client.post(change_url, {'short_info': self.data['short_info']})
+# response = self.client.get(change_url)
+#
+# self.assertEqual(self.user.profile.short_info, self.data['short_info'])
View
2  userprofiles/contrib/profiles/urls.py
@@ -1,4 +1,4 @@
-from django.conf.urls.defaults import patterns, url
+from django.conf.urls import patterns, url
urlpatterns = patterns('userprofiles.contrib.profiles.views',
View
61 userprofiles/contrib/profiles/views.py
@@ -1,40 +1,45 @@
# -*- coding: utf-8 -*-
from django.contrib import messages
-from django.contrib.auth.decorators import login_required
-from django.shortcuts import render_to_response, render, redirect
-from django.template.context import RequestContext
+from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
+from django.views.generic import TemplateView, FormView
-from userprofiles import settings as up_settings
-from userprofiles.utils import get_form_class
+from userprofiles.mixins import LoginRequiredMixin
+from userprofiles.settings import up_settings
+from userprofiles.utils import get_form_class, get_profile_model
-@login_required
-def profile(request):
- return render_to_response('userprofiles/profile.html', {
- 'user': request.user,
- }, context_instance=RequestContext(request))
+class ProfileView(LoginRequiredMixin, TemplateView):
+ template_name = 'userprofiles/profile.html'
+ def get_context_data(self, **kwargs):
+ return {
+ 'user': self.request.user,
+ }
-@login_required
-def profile_change(request):
- ProfileForm = get_form_class(up_settings.PROFILE_FORM)
+profile = ProfileView.as_view()
+
+
+class ProfileChangeView(LoginRequiredMixin, FormView):
+ form_class = get_form_class(up_settings.PROFILE_FORM)
+ template_name = 'userprofiles/profile_change.html'
+
+ def get_form_kwargs(self):
+ kwargs = super(ProfileChangeView, self).get_form_kwargs()
+ kwargs['instance'] = get_profile_model().objects.get(
+ user=self.request.user)
- if request.method == 'POST':
- form = ProfileForm(request.POST, request.FILES,
- instance=request.user.get_profile())
- if form.is_valid():
- profile = form.save()
- messages.success(request, _(u'Profile changed'))
- return redirect(up_settings.PROFILE_CHANGE_DONE_URL)
- else:
if up_settings.REGISTRATION_FULLNAME:
- form = ProfileForm(instance=request.user.get_profile(), initial={
- 'first_name': request.user.first_name,
- 'last_name': request.user.last_name,
- 'email': request.user.email
+ kwargs['initial'].update({
+ 'first_name': self.request.user.first_name,
+ 'last_name': self.request.user.last_name,
+ 'email': self.request.user.email
})
- else:
- form = ProfileForm(instance=request.user.get_profile())
+ return kwargs
+
+ def form_valid(self, form):
+ form.save()
+ messages.success(self.request, _(u'Profile changed'))
+ return redirect(up_settings.PROFILE_CHANGE_DONE_URL)
- return render(request, 'userprofiles/profile_change.html', {'form': form})
+profile_change = ProfileChangeView.as_view()
View
18 userprofiles/forms.py
@@ -2,17 +2,10 @@
import uuid
from django import forms
-from django.utils.translation import ugettext_lazy as _
-from django.conf import settings
from django.contrib.auth.models import User
+from django.utils.translation import ugettext_lazy as _
-from userprofiles import settings as up_settings
-
-if up_settings.USE_ACCOUNT_VERIFICATION:
- from userprofiles.contrib.accountverification.models import AccountVerification
-
-if 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS:
- from userprofiles.contrib.emailverification.models import EmailVerification
+from userprofiles.settings import up_settings
class RegistrationForm(forms.Form):
@@ -81,10 +74,13 @@ def clean_email(self):
new_email = self.cleaned_data['email']
emails = User.objects.filter(email__iexact=new_email).count()
- if 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS:
+
+ if up_settings.USE_EMAIL_VERIFICATION:
+ from userprofiles.contrib.emailverification.models import EmailVerification
emails += EmailVerification.objects.filter(
new_email__iexact=new_email, is_expired=False).count()
+
if emails > 0:
raise forms.ValidationError(
_(u'This email address is already in use. Please supply a different email address.'))
@@ -106,6 +102,8 @@ def clean(self):
def save(self, *args, **kwargs):
if up_settings.USE_ACCOUNT_VERIFICATION:
+ from userprofiles.contrib.accountverification.models import AccountVerification
+
new_user = AccountVerification.objects.create_inactive_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password'],
View
BIN  userprofiles/locale/de/LC_MESSAGES/django.mo
Binary file not shown
View
114 userprofiles/locale/de/LC_MESSAGES/django.po
@@ -7,132 +7,134 @@ msgid ""
msgstr ""
"Project-Id-Version: 0.1\n"
"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2012-02-11 12:02+0100\n"
+"POT-Creation-Date: 2013-03-11 17:26+0100\n"
"PO-Revision-Date: 2012-02-11 12:02+0100\n"
"Last-Translator: Stephan Jaekel <steph@rdev.info>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
+"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"Language: \n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
-#: forms.py:17
+#: forms.py:12
msgid "Username"
msgstr "Benutzername"
-#: forms.py:19
+#: forms.py:14
msgid "This value may contain only letters, numbers and ./-/_ characters."
-msgstr "Dieses Feld darf nur Buchstaben, Ziffern sowie die Zeichen ./-/_ enthalten."
+msgstr ""
+"Dieses Feld darf nur Buchstaben, Ziffern sowie die Zeichen ./-/_ enthalten."
-#: forms.py:21
-#: contrib/profiles/forms.py:12
+#: forms.py:16 contrib/profiles/forms.py:12
msgid "E-mail"
msgstr "E-Mail"
-#: forms.py:22
+#: forms.py:17
msgid "E-mail (repeat)"
msgstr "E-Mail (Wiederholung)"
-#: forms.py:24
+#: forms.py:19
msgid "Password"
msgstr "Passwort"
-#: forms.py:26
+#: forms.py:21
msgid "Password (repeat)"
msgstr "Passwort (Wiederholung)"
-#: forms.py:29
-#: contrib/profiles/forms.py:10
+#: forms.py:24 contrib/profiles/forms.py:10
msgid "First name"
msgstr "Vorname"
-#: forms.py:30
-#: contrib/profiles/forms.py:11
+#: forms.py:25 contrib/profiles/forms.py:11
msgid "Last name"
msgstr "Nachname"
-#: forms.py:48
+#: forms.py:66
msgid "A user with that username already exists."
msgstr "Es existiert bereits ein Benutzer mit diesem Namen."
-#: forms.py:66
-#: contrib/emailverification/forms.py:24
-msgid "This email address is already in use. Please supply a different email address."
-msgstr "Diese E-Mail-Adresse wird bereits verwendet. Bitte geben Sie eine andere E-Mail-Adresse ein."
+#: forms.py:86 contrib/emailverification/forms.py:24
+msgid ""
+"This email address is already in use. Please supply a different email "
+"address."
+msgstr ""
+"Diese E-Mail-Adresse wird bereits verwendet. Bitte geben Sie eine andere E-"
+"Mail-Adresse ein."
-#: forms.py:74
+#: forms.py:94
msgid "The two email addresses do not match."
msgstr "Die beiden E-Mail-Adressen stimmen nicht überein."
-#: forms.py:79
+#: forms.py:99
msgid "You must type the same password each time."
msgstr "Die beiden Passwörter müssen übereinstimmen."
-#: contrib/accountverification/models.py:77
-#: contrib/emailverification/models.py:20
+#: contrib/accountverification/models.py:78
+#: contrib/emailverification/models.py:21
msgid "User"
msgstr "Benutzer"
-#: contrib/accountverification/models.py:78
+#: contrib/accountverification/models.py:79
msgid "Activation key"
msgstr "Aktivierungscode"
-#: contrib/accountverification/models.py:93
+#: contrib/accountverification/models.py:94
msgid "Account verification"
msgstr "Konto-Bestätigung"
-#: contrib/accountverification/models.py:94
+#: contrib/accountverification/models.py:95
msgid "Account verifications"
msgstr "Konto-Bestätigungen"
#: contrib/emailverification/forms.py:14
-#: contrib/emailverification/models.py:22
+#: contrib/emailverification/models.py:23
msgid "New e-mail address"
msgstr "Neue E-Mail Adresse"
-#: contrib/emailverification/models.py:21
+#: contrib/emailverification/models.py:22
msgid "Old e-mail address"
msgstr "Alte E-Mail Adresse"
-#: contrib/emailverification/models.py:24
+#: contrib/emailverification/models.py:25
msgid "Token"
msgstr "Token"
-#: contrib/emailverification/models.py:25
+#: contrib/emailverification/models.py:26
msgid "Code"
msgstr "Code"
-#: contrib/emailverification/models.py:27
+#: contrib/emailverification/models.py:28
msgid "Approved"
msgstr "Bestätigt"
-#: contrib/emailverification/models.py:28
+#: contrib/emailverification/models.py:29
msgid "Expired"
msgstr "Abgelaufen"
-#: contrib/emailverification/models.py:30
+#: contrib/emailverification/models.py:31
msgid "Expiration date"
msgstr "Ablaufdatum"
-#: contrib/emailverification/models.py:50
+#: contrib/emailverification/models.py:51
msgid "E-mail verification"
msgstr "E-Mail Bestätigung"
-#: contrib/emailverification/models.py:51
+#: contrib/emailverification/models.py:52
msgid "E-mail verifications"
msgstr "E-Mail Bestätigungen"
-#: contrib/emailverification/views.py:40
+#: contrib/emailverification/views.py:47
#, python-format
msgid "E-mail address changed to %(email)s"
msgstr "E-Mail Adresse geändert in %(email)s"
-#: contrib/emailverification/views.py:43
+#: contrib/emailverification/views.py:52
msgid "Unable to change e-mail address. Confirmation link is invalid."
-msgstr "E-Mail Adresse kann nicht geändert werden. Bestätigungslink ist ungültig."
+msgstr ""
+"E-Mail Adresse kann nicht geändert werden. Bestätigungslink ist ungültig."
-#: contrib/profiles/views.py:28
+#: contrib/profiles/views.py:42
msgid "Profile changed"
msgstr "Profil aktualisiert"
@@ -148,24 +150,25 @@ msgstr "E-Mail Adresse ändern"
msgid ""
"We send you a e-mail including a link. Please click the link to\n"
" continue changing your e-mail address. Thank you!"
-msgstr "Wir haben Ihnen eine E-Mail mit einem Link zugesandt. Bitte folgen Sie diesem Link, um ihre E-Mail Adresse zu ändern. Danke!"
+msgstr ""
+"Wir haben Ihnen eine E-Mail mit einem Link zugesandt. Bitte folgen Sie "
+"diesem Link, um ihre E-Mail Adresse zu ändern. Danke!"
#: templates/userprofiles/logged_out.html:4
#: templates/userprofiles/logged_out.html:7
msgid "Logged out"
msgstr "Abgemeldet"
-#: templates/userprofiles/login.html:4
-#: templates/userprofiles/login.html:7
-#: templates/userprofiles/login.html:15
+#: templates/userprofiles/login.html:5 templates/userprofiles/login.html:8
+#: templates/userprofiles/login.html:16
msgid "Login"
msgstr "Anmelden"
-#: templates/userprofiles/login.html:17
+#: templates/userprofiles/login.html:18
msgid "No account? Register here."
msgstr "Noch kein Konto? Melden Sie sich hier an."
-#: templates/userprofiles/login.html:18
+#: templates/userprofiles/login.html:19
msgid "No Password? Reset your password here."
msgstr "Passwort vergessen? Setzen Sie Ihr Passwort hier zurück."
@@ -200,16 +203,19 @@ msgstr "Ihr Passwort wurde erfolgreich zurückgesetzt."
#: templates/userprofiles/password_reset_confirm.html:21
msgid "The reset link is invalid. Please double check the link."
-msgstr "Der Passwort-Zurücksetzen-Link ist ungültig. Bitte überprüfen Sie den Link nochmals."
+msgstr ""
+"Der Passwort-Zurücksetzen-Link ist ungültig. Bitte überprüfen Sie den Link "
+"nochmals."
#: templates/userprofiles/password_reset_done.html:10
msgid ""
"We send you a e-mail including a link. Please click the\n"
" link to continue resetting your password. Thank you!"
-msgstr "Wir haben Ihnen eine E-Mail mit einem Link zugesandt. Bitte folgen Sie diesem Link, um ihr Passwort zurückzusetzen. Danke!"
+msgstr ""
+"Wir haben Ihnen eine E-Mail mit einem Link zugesandt. Bitte folgen Sie "
+"diesem Link, um ihr Passwort zurückzusetzen. Danke!"
-#: templates/userprofiles/profile.html:4
-#: templates/userprofiles/profile.html:7
+#: templates/userprofiles/profile.html:4 templates/userprofiles/profile.html:7
msgid "Your profile"
msgstr "Ihr Profil"
@@ -248,12 +254,15 @@ msgstr "Der Aktivierungscode ist ungültig. Die Aktivierung ist nicht möglich."
#: templates/userprofiles/registration_complete.html:11
#, python-format
msgid ""
-"Your registration was successful. We send you a e-mail including a link.<br />\n"
-" Please click the link to activate your account. Thank you!<br />\n"
+"Your registration was successful. We send you a e-mail including a link.<br /"
+">\n"
+" Please click the link to activate your account. Thank you!<br /"
+">\n"
" <br />\n"
" The link is valid for %(expiration_days)s days."
msgstr ""
-"Ihre Registrierung war erfolgreich. Wir haben Ihnen eine E-Mail mit einem Link zugesandt.<br />\n"
+"Ihre Registrierung war erfolgreich. Wir haben Ihnen eine E-Mail mit einem "
+"Link zugesandt.<br />\n"
"Bitte folgen Sie diesem Link, um das Konto zu aktivieren. Danke!<br />\n"
"<br />\n"
"Der Link ist %(expiration_days)s Tage gültig."
@@ -338,7 +347,6 @@ msgstr ""
#~ "\n"
#~ " The link is valid for %(expiration_days)s day.\n"
#~ " "
-
#~ msgid_plural ""
#~ "\n"
#~ " The link is valid for %(expiration_days)s days.\n"
View
11 userprofiles/mixins.py
@@ -0,0 +1,11 @@
+from django.contrib.auth.decorators import login_required
+from django.utils.decorators import method_decorator
+
+
+class LoginRequiredMixin(object):
+ """Ensures that the user is authenticated in order to access the view.
+ http://djangosnippets.org/snippets/2442/"""
+
+ @method_decorator(login_required)
+ def dispatch(self, *args, **kwargs):
+ return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
View
126 userprofiles/settings.py
@@ -1,91 +1,81 @@
# -*- coding: utf-8 -*-
+import sys
+
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
-REGISTRATION_FORM = getattr(
- settings, 'USERPROFILES_REGISTRATION_FORM',
- 'userprofiles.forms.RegistrationForm')
-
-INLINE_PROFILE_ADMIN = getattr(
- settings, 'USERPROFILES_INLINE_PROFILE_ADMIN', False)
-
-DOUBLE_CHECK_EMAIL = getattr(
- settings, 'USERPROFILES_DOUBLE_CHECK_EMAIL', False)
-
-CHECK_UNIQUE_EMAIL = getattr(
- settings, 'USERPROFILES_CHECK_UNIQUE_EMAIL', False)
+class Settings(object):
+ def __init__(self, **kwargs):
+ self.defaults = kwargs
-DOUBLE_CHECK_PASSWORD = getattr(
- settings, 'USERPROFILES_DOUBLE_CHECK_PASSWORD', False)
+ def __getattr__(self, key):
+ return getattr(settings, 'USERPROFILES_%s' % key, self.defaults[key])
-REGISTRATION_FULLNAME = getattr(
- settings, 'USERPROFILES_REGISTRATION_FULLNAME', False)
-# Only use Email field on the form
-EMAIL_ONLY = getattr(
- settings, 'USERPROFILES_EMAIL_ONLY', False)
+up_settings = Settings(
+ REGISTRATION_FORM='userprofiles.forms.RegistrationForm',
+ DOUBLE_CHECK_EMAIL=False,
+ CHECK_UNIQUE_EMAIL=False,
+ DOUBLE_CHECK_PASSWORD=False,
+ REGISTRATION_FULLNAME=False,
+ # Allows user to more easily control where registrations land
+ REGISTRATION_REDIRECT='userprofiles_registration_complete',
-# Automatically log in the user upon registration
-AUTO_LOGIN = getattr(
- settings, 'USERPROFILES_AUTO_LOGIN', False)
+ # Only use Email field on the form
+ EMAIL_ONLY=False,
-# Allows user to more easily control where registrations land
-REGISTRATION_REDIRECT = getattr(
- settings,
- 'USERPROFILES_REDIRECT_ON_REGISTRATION',
- 'userprofiles_registration_complete'
-)
-
-USE_ACCOUNT_VERIFICATION = getattr(
- settings, 'USERPROFILES_USE_ACCOUNT_VERIFICATION', False)
+ # Automatically log in the user upon registration
+ AUTO_LOGIN=False,
-if (USE_ACCOUNT_VERIFICATION and
- 'userprofiles.contrib.accountverification' not in settings.INSTALLED_APPS):
- raise ImproperlyConfigured('You need to add `userprofiles.contrib.accountverification` '
- 'to INSTALLED_APPS to use account verification.')
+ USE_ACCOUNT_VERIFICATION=False,
+ ACCOUNT_VERIFICATION_DAYS=7,
-# These settings together make no sense
-if USE_ACCOUNT_VERIFICATION and AUTO_LOGIN:
- raise ImproperlyConfigured("You cannot use autologin with account verification")
+ USE_EMAIL_VERIFICATION=False,
+ EMAIL_VERIFICATION_DAYS=2,
+ EMAIL_VERIFICATION_DONE_URL='userprofiles_email_change',
-ACCOUNT_VERIFICATION_DAYS = getattr(
- settings, 'USERPROFILES_ACCOUNT_VERIFICATION_DAYS', 7)
+ USE_PROFILE=False,
+ PROFILE_FORM='userprofiles.contrib.profiles.forms.ProfileForm',
+ PROFILE_ALLOW_EMAIL_CHANGE=False,
+ PROFILE_CHANGE_DONE_URL='userprofiles_profile_change',
+ INLINE_PROFILE_ADMIN=False,
+)
-EMAIL_VERIFICATION_DAYS = getattr(
- settings, 'USERPROFILES_EMAIL_VERIFICATION_DAYS', 2)
-
-EMAIL_VERIFICATION_DONE_URL = getattr(
- settings, 'USERPROFILES_EMAIL_VERIFICATION_DONE_URL',
- 'userprofiles_email_change')
+def validate_settings():
+ if (up_settings.USE_ACCOUNT_VERIFICATION and
+ 'userprofiles.contrib.accountverification' not in settings.INSTALLED_APPS):
+ raise ImproperlyConfigured('You need to add `userprofiles.contrib.accountverification` '
+ 'to INSTALLED_APPS to use account verification.')
-USE_PROFILE = getattr(
- settings, 'USERPROFILES_USE_PROFILE', False)
+ # These settings together make no sense
+ if up_settings.USE_ACCOUNT_VERIFICATION and up_settings.AUTO_LOGIN:
+ raise ImproperlyConfigured("You cannot use autologin with account verification")
-if not USE_PROFILE and 'userprofiles.contrib.profiles' in settings.INSTALLED_APPS:
- raise ImproperlyConfigured('You need to activate profiles to use '
- '`userprofiles.contrib.accountverification`')
+ if up_settings.USE_PROFILE and 'userprofiles.contrib.profiles' not in settings.INSTALLED_APPS:
+ raise ImproperlyConfigured('You need to add `userprofiles.contrib.profiles` '
+ 'to INSTALLED_APPS to use profiles.')
-PROFILE_FORM = getattr(
- settings, 'USERPROFILES_PROFILE_FORM',
- 'userprofiles.contrib.profiles.forms.ProfileForm')
+ if up_settings.PROFILE_ALLOW_EMAIL_CHANGE and up_settings.CHECK_UNIQUE_EMAIL:
+ raise ImproperlyConfigured(
+ 'USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE cannot be activated '
+ 'when USERPROFILES_CHECK_UNIQUE_EMAIL is active.')
-PROFILE_ALLOW_EMAIL_CHANGE = getattr(
- settings, 'USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE', False)
+ if (up_settings.USE_EMAIL_VERIFICATION and
+ 'userprofiles.contrib.emailverification' not in settings.INSTALLED_APPS):
+ raise ImproperlyConfigured('You need to add `userprofiles.contrib.emailverification` '
+ 'to INSTALLED_APPS to use emailverification.')
-if PROFILE_ALLOW_EMAIL_CHANGE and CHECK_UNIQUE_EMAIL:
- raise ImproperlyConfigured(
- 'USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE cannot be activated '
- 'when USERPROFILES_CHECK_UNIQUE_EMAIL is active.')
+ if up_settings.PROFILE_ALLOW_EMAIL_CHANGE and up_settings.USE_EMAIL_VERIFICATION:
+ raise ImproperlyConfigured(
+ 'USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE cannot be activated '
+ 'when USERPROFILES_USE_EMAIL_VERIFICATION is activated.')
-if (PROFILE_ALLOW_EMAIL_CHANGE
- and 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS):
- raise ImproperlyConfigured(
- 'USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE cannot be activated '
- 'when `userprofiles.contrib.emailverification` is used.')
+ if ('test' not in sys.argv and not up_settings.USE_EMAIL_VERIFICATION and
+ 'userprofiles.contrib.emailverification' in settings.INSTALLED_APPS):
+ raise ImproperlyConfigured('You need to set USERPROFILES_USE_EMAIL_VERIFICATION '
+ 'to use `userprofiles.contrib.emailverification`')
-PROFILE_CHANGE_DONE_URL = getattr(
- settings, 'USERPROFILES_PROFILE_CHANGE_DONE_URL',
- 'userprofiles_profile_change')
+validate_settings()
View
5 userprofiles/templates/userprofiles/login.html
@@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
+{% load url from future %}
{% block title %}{% trans "Login" %}{% endblock %}
@@ -14,8 +15,8 @@
<fieldset class="submit-row">
<p><button type="submit">{% trans "Login" %}</button></p>
<ul>
- <li><a href="{% url userprofiles_registration %}">{% trans "No account? Register here." %}</a></li>
- <li><a href="{% url auth_password_reset %}">{% trans "No Password? Reset your password here." %}</a></li>
+ <li><a href="{% url 'userprofiles_registration' %}">{% trans "No account? Register here." %}</a></li>
+ <li><a href="{% url 'auth_password_reset' %}">{% trans "No Password? Reset your password here." %}</a></li>
</ul>
</fieldset>
</form>
View
2  userprofiles/templates/userprofiles/mails/activation_email.html
@@ -1,4 +1,4 @@
-{% load i18n %}{% url userprofiles_registration_activate activation_key as activation_url %}{% blocktrans with url=activation_url domain=site.domain %}Thank you for creating an account.
+{% load i18n %}{% load url from future %}{% url 'userprofiles_registration_activate' activation_key as activation_url %}{% blocktrans with url=activation_url domain=site.domain %}Thank you for creating an account.
Please click on the following link to activate your account:
View
2  userprofiles/templates/userprofiles/mails/emailverification.html
@@ -1,4 +1,4 @@
-{% load i18n %}{% url userprofiles_email_change_approve verification.token, verification.code as activation_url %}{% blocktrans with url=activation_url domain=site.domain %}Please click on the following link to change your email address:
+{% load i18n %}{% load url from future %}{% url 'userprofiles_email_change_approve' verification.token verification.code as activation_url %}{% blocktrans with url=activation_url domain=site.domain %}Please click on the following link to change your email address:
http://{{ domain }}{{ url }}
View
2  userprofiles/templates/userprofiles/mails/password_reset_email.html
@@ -1,4 +1,4 @@
-{% load i18n %}{% url auth_password_reset_confirm uidb36=uid, token=token as url%}{% blocktrans with protocol=protocol domain=domain url=url %}Please click on the following link to reset your password:
+{% load i18n %}{% load url from future %}{% url 'auth_password_reset_confirm' uid token as url%}{% blocktrans with protocol=protocol domain=domain url=url %}Please click on the following link to reset your password:
{{ protocol }}://{{ domain }}{{ url }}
View
2  userprofiles/tests/__init__.py
@@ -1,2 +0,0 @@
-from userprofiles.tests.views import *
-from userprofiles.tests.forms import *
View
37 userprofiles/tests/forms.py
@@ -1,37 +0,0 @@
-from django.test import TestCase
-
-from userprofiles.forms import RegistrationForm
-from userprofiles import settings as up_settings
-
-
-class RegistrationFormTests(TestCase):
- """ Test Registration Form against settings """
-
- def test_email_repeat(self):
- form_without = RegistrationForm()
- self.assertFalse('email_repeat' in form_without.fields.keys())
-
- up_settings.DOUBLE_CHECK_EMAIL = True
- form_with = RegistrationForm()
- self.assertTrue('email_repeat' in form_with.fields.keys())
- up_settings.DOUBLE_CHECK_EMAIL = False
-
- def test_password_repeat(self):
- form_without = RegistrationForm()
- self.assertFalse('password_repeat' in form_without.fields.keys())
-
- up_settings.DOUBLE_CHECK_PASSWORD = True
- form_with = RegistrationForm()
- self.assertTrue('password_repeat' in form_with.fields.keys())
- up_settings.DOUBLE_CHECK_PASSWORD = False
-
- def test_fullname(self):
- form_without = RegistrationForm()
- self.assertFalse('first_name' in form_without.fields.keys())
- self.assertFalse('last_name' in form_without.fields.keys())
-
- up_settings.REGISTRATION_FULLNAME = True
- form_with = RegistrationForm()
- self.assertTrue('first_name' in form_with.fields.keys())
- self.assertTrue('last_name' in form_with.fields.keys())
- up_settings.REGISTRATION_FULLNAME = False
View
23 userprofiles/tests/runtests.py
@@ -1,23 +0,0 @@
-#!/usr/bin/env python
-import os
-import sys
-
-from django.conf import settings
-from django.test.simple import DjangoTestSuiteRunner
-
-def runtests(*test_args):
- if not test_args:
- test_args = ['userprofiles']
- parent = os.path.join(
- os.path.dirname(os.path.abspath(__file__)),
- "..",
- "..",
- )
- sys.path.insert(0, parent)
- runner = DjangoTestSuiteRunner()
- failures = runner.run_tests(test_args, verbosity=1, interactive=True)
- sys.exit(failures)
-
-
-if __name__ == '__main__':
- runtests(*sys.argv[1:])
View
35 userprofiles/tests/test_auth_backends.py
@@ -0,0 +1,35 @@
+from django.contrib.auth import authenticate
+from django.contrib.auth.models import User
+from django.test import TestCase
+from django.test.utils import override_settings
+
+
+class AuthBackendTests(TestCase):
+ def setUp(self):
+ self.existing_user = User.objects.create_user(username='test',
+ email='test@example.com', password='password')
+
+ def tearDown(self):
+ self.existing_user.delete()
+
+ def test_without_email_auth_backend(self):
+ user = authenticate(username='test2', password='password2')
+ self.assertEqual(user, None)
+
+ user = authenticate(username='test', password='password')
+ self.assertEqual(user, self.existing_user)
+
+ user = authenticate(username='test@example.com', password='password')
+ self.assertEqual(user, None)
+
+ @override_settings(AUTHENTICATION_BACKENDS=[
+ 'userprofiles.auth_backends.EmailOrUsernameModelBackend'])
+ def test_with_email_auth_backend(self):
+ user = authenticate(username='test2', password='password2')
+ self.assertEqual(user, None)
+
+ user = authenticate(username='test', password='password')
+ self.assertEqual(user, self.existing_user)
+
+ user = authenticate(username='test@example.com', password='password')
+ self.assertEqual(user, self.existing_user)
View
187 userprofiles/tests/test_forms.py
@@ -0,0 +1,187 @@
+from django.contrib.auth.models import User
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from userprofiles.contrib.accountverification.models import AccountVerification
+from userprofiles.contrib.emailverification.models import EmailVerification
+from userprofiles.forms import RegistrationForm
+
+
+class RegistrationFormTests(TestCase):
+ """ Test Registration Form against settings """
+
+ def setUp(self):
+ self.existing_user = User.objects.create(username='existinguser',
+ email='existingemail@example.com')
+
+ def tearDown(self):
+ self.existing_user.delete()
+
+ def test_email_repeat_disabled(self):
+ form = RegistrationForm()
+ self.assertFalse('email_repeat' in form.fields.keys())
+
+ @override_settings(USERPROFILES_DOUBLE_CHECK_EMAIL=True)
+ def test_email_repeat_enabled(self):
+ form = RegistrationForm()
+ self.assertTrue('email_repeat' in form.fields.keys())
+
+ def test_password_repeat_disabled(self):
+ form = RegistrationForm()
+ self.assertFalse('password_repeat' in form.fields.keys())
+
+ @override_settings(USERPROFILES_DOUBLE_CHECK_PASSWORD=True)
+ def test_password_repeat_enabled(self):
+ form = RegistrationForm()
+ self.assertTrue('password_repeat' in form.fields.keys())
+
+ def test_fullname_disabled(self):
+ form = RegistrationForm()
+ self.assertFalse('first_name' in form.fields.keys())
+ self.assertFalse('last_name' in form.fields.keys())
+
+ @override_settings(USERPROFILES_REGISTRATION_FULLNAME=True)
+ def test_fullname_enabled(self):
+ form = RegistrationForm()
+ self.assertTrue('first_name' in form.fields.keys())
+ self.assertTrue('last_name' in form.fields.keys())
+
+ def test_clean_username_email_only_disabled(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ form = RegistrationForm({
+ 'username': 'existinguser',
+ 'email': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertFalse(form.is_valid())
+
+ def test_clean_email_unique_disabled(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'existingemail@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ @override_settings(USERPROFILES_CHECK_UNIQUE_EMAIL=True)
+ def test_clean_email_unique_enabled(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'existingemail@example.com',
+ 'password': 'password'
+ })
+ self.assertFalse(form.is_valid())
+
+ @override_settings(USERPROFILES_CHECK_UNIQUE_EMAIL=True,
+ USERPROFILES_USE_EMAIL_VERIFICATION=True)
+ def test_clean_email_unique_enabled_with_emailverification(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'existingemail2@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ EmailVerification.objects.create(user=self.existing_user,
+ old_email=self.existing_user.email, new_email='existingemail2@example.com')
+
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'existingemail2@example.com',
+ 'password': 'password'
+ })
+ self.assertFalse(form.is_valid())
+
+ @override_settings(USERPROFILES_DOUBLE_CHECK_EMAIL=True)
+ def test_double_check_email(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'email_repeat': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'email_repeat': 'test2@example.com',
+ 'password': 'password'
+ })
+ self.assertFalse(form.is_valid())
+
+ @override_settings(USERPROFILES_DOUBLE_CHECK_PASSWORD=True)
+ def test_double_check_password(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password',
+ 'password_repeat': 'password'
+ })
+ self.assertTrue(form.is_valid())
+
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password',
+ 'password_repeat': 'password2'
+ })
+ self.assertFalse(form.is_valid())
+
+ def test_form_save(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+ new_user = form.save()
+
+ self.assertEqual(new_user.username, 'test')
+ self.assertTrue(new_user.is_active)
+
+ @override_settings(USERPROFILES_USE_ACCOUNT_VERIFICATION=True)
+ def test_form_save_with_account_verification(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password'
+ })
+ self.assertTrue(form.is_valid())
+ new_user = form.save()
+
+ self.assertEqual(new_user.username, 'test')
+ self.assertFalse(new_user.is_active)
+
+ self.assertEqual(AccountVerification.objects.count(), 1)
+
+ @override_settings(USERPROFILES_REGISTRATION_FULLNAME=True)
+ def test_form_save_with_fullname(self):
+ form = RegistrationForm({
+ 'username': 'test',
+ 'email': 'test@example.com',
+ 'password': 'password',
+ 'first_name': 'First',
+ 'last_name': 'Last',
+ })
+ self.assertTrue(form.is_valid())
+ new_user = form.save()
+
+ self.assertEqual(new_user.username, 'test')
+ self.assertTrue(new_user.is_active)
+
+ self.assertEqual(new_user.first_name, 'First')
+ self.assertEqual(new_user.last_name, 'Last')
View
41 userprofiles/tests/test_settings.py
@@ -0,0 +1,41 @@
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from userprofiles.settings import validate_settings
+
+
+class SettingsTests(TestCase):
+ @override_settings(USERPROFILES_USE_ACCOUNT_VERIFICATION=True,
+ INSTALLED_APPS=list(set(settings.INSTALLED_APPS) - set(
+ ['userprofiles.contrib.accountverification'])))
+ def test_account_verification(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
+
+ @override_settings(USERPROFILES_USE_ACCOUNT_VERIFICATION=True,
+ USERPROFILES_AUTO_LOGIN=True)
+ def test_account_verification_auto_login(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
+
+ @override_settings(USERPROFILES_USE_PROFILE=True,
+ INSTALLED_APPS=list(set(settings.INSTALLED_APPS) - set(
+ ['userprofiles.contrib.profiles'])))
+ def test_profile(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
+
+ @override_settings(USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE=True,
+ USERPROFILES_CHECK_UNIQUE_EMAIL=True)
+ def test_profile_email_check(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
+
+ @override_settings(USERPROFILES_USE_EMAIL_VERIFICATION=True,
+ INSTALLED_APPS=list(set(settings.INSTALLED_APPS) - set(
+ ['userprofiles.contrib.emailverification'])))
+ def test_email_verification(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
+
+ @override_settings(USERPROFILES_USE_EMAIL_VERIFICATION=True,
+ USERPROFILES_PROFILE_ALLOW_EMAIL_CHANGE=True)
+ def test_email_verification_allow_email_change(self):
+ self.assertRaises(ImproperlyConfigured, validate_settings)
View
38 userprofiles/tests/test_utils.py
@@ -0,0 +1,38 @@
+from django.conf import settings
+from django.contrib.auth.models import SiteProfileNotAvailable
+from django.core.exceptions import ImproperlyConfigured
+from django.db.models import get_model
+from django.test import TestCase
+from django.test.utils import override_settings
+
+from userprofiles import forms
+from userprofiles import utils
+
+
+class UtilsTests(TestCase):
+ def test_get_profile_module_disabled(self):
+ self.assertEqual(utils.get_profile_model(), None)
+
+ @override_settings(USERPROFILES_USE_PROFILE=True)
+ def test_get_profile_module_enabled(self):
+ settings.AUTH_PROFILE_MODULE = None
+ self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
+
+ settings.AUTH_PROFILE_MODULE = 'test_project.test_accounts.Profile'
+ self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
+
+ settings.AUTH_PROFILE_MODULE = 'test_accounts.InvalidProfile'
+ self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
+
+ settings.AUTH_PROFILE_MODULE = 'test_accounts.Profile'
+ self.assertEqual(utils.get_profile_model(), get_model('test_accounts', 'Profile'))
+
+ def test_get_form_class(self):
+ self.assertEqual(utils.get_form_class('userprofiles.forms.RegistrationForm'),
+ forms.RegistrationForm)
+
+ self.assertRaises(ImproperlyConfigured,
+ utils.get_form_class, 'userprofiles.invalid_forms.RegistrationForm')
+
+ self.assertRaises(ImproperlyConfigured,
+ utils.get_form_class, 'userprofiles.forms.InvalidRegistrationForm')
View
31 userprofiles/tests/views.py → userprofiles/tests/test_views.py
@@ -1,11 +1,12 @@
-from django.test import TestCase
-from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
+from django.core.urlresolvers import reverse
+from django.test import TestCase
+from django.test.utils import override_settings
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
-class SimpleViewTests(TestCase):
+class ViewTests(TestCase):
def setUp(self):
self.data = {
'username': 'newuser',
@@ -23,17 +24,19 @@ def test_registration(self):
self.assertEqual(response.status_code, 200)
response = self.client.post(url, data=self.data)
+
self.assertEqual(response.status_code, 302)
self.assertRedirects(response,
reverse(up_settings.REGISTRATION_REDIRECT))
self.assertTrue(User.objects.get(username='newuser'))
+ @override_settings(USERPROFILES_EMAIL_ONLY=True)
def test_email_only_registration(self):
- up_settings.EMAIL_ONLY = True
-
url = reverse('userprofiles_registration')
response = self.client.get(url)
- self.assertTrue('<input type="hidden" name="username"' in response.content)
+
+ self.assertTrue('<input type="hidden" name="username"' in response.content or
+ '<input id="id_username" name="username" type="hidden" />' in response.content)
data = self.data
data['username'] = ''
@@ -45,11 +48,8 @@ def test_email_only_registration(self):
user = User.objects.get(email=data['email'])
self.assertNotEqual(user.username, self.data['username'])
- up_settings.EMAIL_ONLY = False
-
+ @override_settings(USERPROFILES_AUTO_LOGIN=True)
def test_auto_login(self):
- up_settings.AUTO_LOGIN = True
-
url = reverse('userprofiles_registration')
response = self.client.post(url, data=self.data)
self.assertEqual(response.status_code, 302)
@@ -59,12 +59,8 @@ def test_auto_login(self):
user = User.objects.get(username=self.data['username'])
self.assertTrue(user.is_authenticated())
- up_settings.AUTO_LOGIN = False
-
+ @override_settings(USERPROFILES_AUTO_LOGIN=True, USERPROFILES_EMAIL_ONLY=True)
def test_email_and_auto_login(self):
- up_settings.EMAIL_ONLY = True
- up_settings.AUTO_LOGIN = True
-
url = reverse('userprofiles_registration')
response = self.client.post(url, data=self.data)
self.assertEqual(response.status_code, 302)
@@ -74,9 +70,6 @@ def test_email_and_auto_login(self):
user = User.objects.get(email=self.data['email'])
self.assertTrue(user.is_authenticated())
- up_settings.EMAIL_ONLY = False
- up_settings.AUTO_LOGIN = False
-
def test_registration_complete(self):
""" Simple test to make sure this renders """
response = self.client.get(reverse('userprofiles_registration_complete'))
View
3  userprofiles/urls.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
-from django.conf.urls.defaults import patterns, url, include
-
from django.conf import settings
+from django.conf.urls import patterns, url, include
urlpatterns = patterns('userprofiles.views',
View
11 userprofiles/utils.py
@@ -1,9 +1,9 @@
-from django.db import models
from django.conf import settings
-from userprofiles import settings as up_settings
-
-from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth.models import SiteProfileNotAvailable
+from django.core.exceptions import ImproperlyConfigured
+from django.db import models
+
+from userprofiles.settings import up_settings
try:
from importlib import import_module
@@ -38,9 +38,10 @@ def get_profile_model():
UserProfile = get_profile_model()
+
def get_form_class(path):
i = path.rfind('.')
- module, attr = path[:i], path[i+1:]
+ module, attr = path[:i], path[i + 1:]
try:
mod = import_module(module)
except ImportError, e:
View
57 userprofiles/views.py
@@ -1,44 +1,43 @@
# -*- coding: utf-8 -*-
-from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
+from django.shortcuts import redirect
+from django.views.generic import FormView, TemplateView
-from userprofiles import settings as up_settings
+from userprofiles.settings import up_settings
from userprofiles.utils import get_form_class
-def registration(request):
- RegistrationForm = get_form_class(up_settings.REGISTRATION_FORM)
+class RegistrationView(FormView):
+ form_class = get_form_class(up_settings.REGISTRATION_FORM)
+ template_name = 'userprofiles/registration.html'
- if request.method == 'POST':
- form = RegistrationForm(data=request.POST, files=request.FILES)
+ def form_valid(self, form):
+ form.save()
+ username = form.cleaned_data['username']
+ password = form.cleaned_data['password']
- if form.is_valid():
- new_user = form.save()
- username = form.cleaned_data['username']
- password = form.cleaned_data['password']
+ # Automatically log this user in
+ if up_settings.AUTO_LOGIN:
+ if up_settings.EMAIL_ONLY:
+ username = form.cleaned_data['email']
- # Automatically log this user in
- if up_settings.AUTO_LOGIN:
+ user = authenticate(username=username, password=password)
+ if user is not None:
+ if user.is_active:
+ login(self.request, user)
- if up_settings.EMAIL_ONLY:
- username = form.cleaned_data['email']
+ return redirect(up_settings.REGISTRATION_REDIRECT)
- user = authenticate(username=username, password=password)
- if user is not None:
- if user.is_active:
- login(request, user)
+registration = RegistrationView.as_view()
- return redirect(up_settings.REGISTRATION_REDIRECT)
- else:
- form = RegistrationForm()
+class RegistrationCompleteView(TemplateView):
+ template_name = 'userprofiles/registration_complete.html'
- return render(request, 'userprofiles/registration.html', {
- 'form': form
- })
+ def get_context_data(self, **kwargs):
+ return {
+ 'account_verification_active': up_settings.USE_ACCOUNT_VERIFICATION,
+ 'expiration_days': up_settings.ACCOUNT_VERIFICATION_DAYS,
+ }
-def registration_complete(request):
- return render(request, 'userprofiles/registration_complete.html', {
- 'account_verification_active': up_settings.USE_ACCOUNT_VERIFICATION,
- 'expiration_days': up_settings.ACCOUNT_VERIFICATION_DAYS,
- })
+registration_complete = RegistrationCompleteView.as_view()
Please sign in to comment.
Something went wrong with that request. Please try again.