Skip to content

Instantly share code, notes, and snippets.

@mx-moth
Created May 1, 2017 07:16
Show Gist options
  • Save mx-moth/25e861bdfc87ee7ea94769dda2febc56 to your computer and use it in GitHub Desktop.
Save mx-moth/25e861bdfc87ee7ea94769dda2febc56 to your computer and use it in GitHub Desktop.
from django.core.exceptions import ValidationError
from django import forms
class UsernameValidatorForm(forms.Form):
username = forms.CharField()
def clean_username(self):
username = self.cleaned_data['username']
## Character pattern, or regex, set to 'characters' for use later to make sure username contains only letters or digits with one optional space anywhere in between, and begins and ends with only letters or digits.
characters = re.compile(r'^[\d|\w]+[\s{1}]?[\d|\w]+$')
if not re.match(characters, username):
raise ValidationError("Usernames can only contain characters ...")
## Get 'username' length to test later since usernames need to be checked for both having only the correct characters AND to be of the correct length.
length = len(username)
## Valid returns true? Then check to see if size requirements are met, modifying 'valid' if not.
if not (8 <= length <= 16):
raise ValidationError("Usernames must be between 8 and 16 characters long")
return username
from django.shortcuts import redirect, render
from .forms import UsernameValidatorForm
from .models import User
def index(request, username = None):
if request.method == 'POST':
# The visitor has submitted a form! Hurrah
form = UsernameValidatorForm(request.POST)
# Is the data in the form valid?
if form.is_valid():
# The form is valid! Great success. Do something with the data
pass
# Now redirect the user somewhere useful
return redirect('Name:success')
else:
# Bad luck, show an error message
messages.error(request, 'There was an error validating your username')
else:
# Make an empty form for new visitors
form = UsernameValidatorForm()
## Make sure messages gets added to 'render()' once templates and routing are complete.
return render(request, 'name/index.html', {
'form': form,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment