snipt/utils/forms.py

45 lines
1.6 KiB
Python
Raw Normal View History

2015-07-24 18:39:25 -07:00
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationForm
2015-07-24 18:28:31 -07:00
class SniptRegistrationForm(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses and further restricts usernames.
"""
2019-01-23 15:52:55 -08:00
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
2019-01-23 15:52:55 -08:00
existing = User.objects.filter(username__iexact=self.cleaned_data["username"])
if existing.exists():
2019-01-23 15:52:55 -08:00
raise forms.ValidationError(_("A user with that username already exists."))
2019-01-23 15:52:55 -08:00
elif "@" in self.cleaned_data["username"]:
raise forms.ValidationError(_("Cannot have '@' in username."))
2019-01-23 15:52:55 -08:00
elif "." in self.cleaned_data["username"]:
raise forms.ValidationError(_("Cannot have '.' in username."))
2019-01-23 15:52:55 -08:00
elif "+" in self.cleaned_data["username"]:
raise forms.ValidationError(_("Cannot have '+' in username."))
else:
2019-01-23 15:52:55 -08:00
return self.cleaned_data["username"]
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
2019-01-23 15:52:55 -08:00
if User.objects.filter(email__iexact=self.cleaned_data["email"]):
2015-07-24 18:28:31 -07:00
raise forms.ValidationError(
2019-01-23 15:52:55 -08:00
_(
"""This email address is already in use. Please supply a
different email address."""
)
)
return self.cleaned_data["email"]