Skip to content

Instantly share code, notes, and snippets.

@joseph-montanez
Created September 1, 2016 11:11
Show Gist options
  • Save joseph-montanez/38109ce4cf3fabde50b5ab0ac921ed94 to your computer and use it in GitHub Desktop.
Save joseph-montanez/38109ce4cf3fabde50b5ab0ac921ed94 to your computer and use it in GitHub Desktop.
How to set email as required, if from a model?
from django.contrib.auth.models import User
from django import forms
from django.core.exceptions import ValidationError
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password')
def __init__(self, *args, **kwargs):
super(forms.ModelForm, self).__init__(*args, **kwargs)
self.fields['first_name'].widget = forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'First Name'
})
self.fields['last_name'].widget = forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Last Name'
})
def clean_email(self):
email = self.cleaned_data['email']
if len(email) == 0:
raise ValidationError("email cannot be empty")
return email
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment