jayko03
jayko03

Reputation: 2481

Django1.11 Customized UserCreationForm filter email

I am trying to filter user's alias. I am using Django's userform and its authentication.

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignupForm(UserCreationForm):
    email = forms.CharField(
        retuired=True,
        widget=EmailInput(
            attrs={'class':'validate',}
        )
    )

views.py

from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login as auth_login

def signup(req):
    if req.method == "POST":
        form = UserCreationForm(req.POST)
        if form.is_valid():
            user = form.save()
            auth_login(req, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    context = {
        'form':form,
    }
    return render(req, "signup.html", context)

I believe that I need to filter inside of views.py.
For example, if I want to filter alias which is not gmail, they cannot signup. How can I filter email?

Thanks in advance!

Upvotes: 0

Views: 72

Answers (1)

tell k
tell k

Reputation: 615

You can use clean_<field_name> method.

def clean_email(self):
    email = self.cleaned_data['email']
    if not email.endswith('gmail.com'):
       raise forms.ValidationError("Invalid email", code='invalid email')
    return email

https://docs.djangoproject.com/en/1.11/ref/forms/validation/#cleaning-a-specific-field-attribute

Upvotes: 1

Related Questions