- Author:
- ElfSternberg
- Posted:
- June 26, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 1 (after 1 ratings)
This code overrides the existing RegistrationForm in django-registration and adds a new validation step. In this step, the username (my example slug) is compared against all the existing URLs that the application currently resolves and, if it does successfully resolve, throws a validation exception. This indicates that the username chosen would be overriden (or, if you wrote your urls.py file badly, would override) an existing URL already recognized by your application.
A much longer explanation can be found at Dynamic names as first-level URL path objects in Django.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # Somewhere in your application:
from registration.forms import RegistrationForm
from django.forms import ValidationError
from django.core.urlresolvers import resolve, Resolver404
from urlparse import urlparse
class NewRegistrationForm(RegistrationForm):
# Ensures than any usernames added will not
# conflict with existing commands.
def clean_username(self):
username = super(NewRegistrationForm, self).clean_username()
try: resolve(urlparse('/' + username + '/')[2])
except Resolver404, e:
return username
raise ValidationError(
(u'This username does not create '
u'a valid URL. Please choose '
u'another'))
# in urls.py:
url(r'^accounts/register/$',
'registration.views.register',
{ 'form_class': NewRegistrationForm },
name = 'registration_register')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.