the code below is a simple register for an account now when I submit this form it redirects me to the home page and this means that my form is valid and works but when I check my Admin page I see that account is not registered and I get no error. therefor I can understand here that my code is already working but it hasn't been saved.
so, how can I save member through FormView?
thanks in advance
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from django.views.generic.edit import FormView, CreateView
from .forms import UserForm
from .models import User
from django.urls import reverse_lazy
class IndexView(TemplateView):
template_name = "accounts/index.html"
class ProfileView(CreateView):
template_name = 'accounts/register.html'
success_url = reverse_lazy('accounts:index')
form_class = UserForm
forms.py
from django import forms
from .models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput)
class Meta:
model = User
fields = '__all__'
exclude = ('staff', 'active', 'admin', 'last_login')
def clean_password2(self):
password = self.cleaned_data['password']
password2 = self.cleaned_data['password2']
if password and password2 and password != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def clean_email(self):
email = self.cleaned_data['email']
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password'])
if commit:
user.save()
return user
models.py
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager)
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserManager(BaseUserManager):
def create_user(self, email, password, username, is_staff=True, is_admin=True, is_active=True):
if not email:
raise ValueError("This email is invalid")
if not password:
raise ValueError("This Password is invalid")
if not username:
raise ValueError("This Username is invalid")
user = self.model(
email=self.normalize_email(email)
)
user.staff = is_staff
user.admin = is_admin
user.active = is_active
user.set_password(password)
user.username = username
user.save(using=self._db)
return user
def create_staffuser(self, email, password, username):
user = self.create_user(
email,
password=password,
username=username,
is_staff=True,
)
return user
def create_superuser(self, email, password, username):
user = self.create_user(
email=email,
password=password,
username=username,
is_staff=True,
is_admin=True,
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True, verbose_name="Email")
first_name = models.CharField(max_length=255, verbose_name="First Name")
last_name = models.CharField(max_length=255, verbose_name="Last Name")
username = models.CharField(max_length=50, unique=True, verbose_name="Username")
active = models.BooleanField(default=True, verbose_name="Active")
staff = models.BooleanField(default=False, verbose_name="Staff")
admin = models.BooleanField(default=False, verbose_name="Admin")
timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Time Stamp")
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
objects = UserManager()
def __str__(self):
return self.username
def get_short_name(self):
return self.username
def get_full_name(self):
return self.username
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
article = models.TextField(blank=True, max_length=500, verbose_name="Article")
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = User.objects.create(user=kwargs['instance'])
post_save.connect(receiver=create_profile, sender=User)
Because a FormView doesn't save() the form. It's meant to be used with any form, not just ModelForms. Not every Form has a save() method.
The only thing the FormView does in form_valid() is redirect to the success url. You have to tell it yourself what you it to do after the form was verified to be valid:
def form_valid(self, form):
form.save()
return super().form_valid(form)
You can see the inner workings of FormView here.
You could use a CreateView instead of a FormView. That would do the saving for you.
Related
I am trying to implement a custom user model. Whenever I try to log in for a user (created using the registration form), it returns no user.
but if I create a user using the admin panel then the login function works perfectly.
I think the problem is with password hashing. Tried some solve from here and there but seems like I can't find what I am looking for.
The problem I am having :
email: yeamin21#outlook.com
pass: 1234 works (created using admin panel)
but, email: yeamin21#outlook.com
pass: hashed(1234) does not (created using the registration form)
models.py
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractBaseUser):
username = models.CharField(max_length=30,unique=True)
email = models.EmailField(verbose_name='Email',unique=True)
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
def __str__(self):
return self.name
class Restaurant(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
location = models.CharField(max_length=200)
def __str__(self):
return self.user.email
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from Customer.models import User, Restaurant
class RestaurantSignUpForm(UserCreationForm):
class Meta(UserCreationForm):
model = User
fields = ['email','name','username']
#transaction.atomic
def save(self, commit=True):
user = super().save(commit=False)
user.is_restaurant=True
user.is_active=True
user.save()
restaurant = Restaurant.objects.create(user=user)
restaurant.save()
return user
backend.py
from django.contrib.auth.backends import BaseBackend, ModelBackend
from Customer.models import User
class CustomBackend(ModelBackend):
def authenticate(self,email=None,password=None):
try:
user=User.objects.get(email=email)
print('active')
if user.check_password(password) is True:
return user
except User.DoesNotExist:
return None
return User.objects.get(email=User.email)
def get_user(self, email):
try:
return User.objects.get(email)
except User.DoesNotExist:
return None
views.py
from django.contrib.auth import login, authenticate
from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
from Customer.forms import RestaurantSignUpForm
from Customer.models import User
def login_page(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
print(user)
if user is not None:
login(request, user)
return HttpResponse("Logged in")
else:
print(user)
context = {}
return render(request, 'login.html', context)
The problem is fixed
thanks to this https://stackoverflow.com/a/48971226/10602634
def authenticate(self, request, email=None, password=None):
try:
user= User.objects.get(email=email)
if check_password(password, user.password):
return user
except User.DoesNotExist:
return None
i have made a custom user model. using that model i have made a login form, signup form. but sign up form and logout works fine. but whenever i try to submit login form it does not authenticate. where is the problem? there is two authentication one is in for login in forms.py other is in views.py for login
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from diabetes.models import UserSignupModel
from django.contrib.auth import login,authenticate,logout
class UserSignupForm(UserCreationForm):
email=forms.EmailField(max_length=60,help_text="add a valid email address",required=True)
name=forms.CharField(max_length=15,help_text="add a valid name")
age=forms.CharField(max_length=15)
class Meta:
model=UserSignupModel
fields=('email','name',"username",'age',"password1","password2")
class UserLoginForm(forms.ModelForm):
password=forms.CharField(label="password",widget=forms.PasswordInput)
class Meta:
model=UserSignupModel
fields=("email","password")
def clean(self):
if self.is_valid():
email=self.cleaned_data['email']
password=self.cleaned_data['password']
if not authenticate(email=email,password=password,backend='django.contrib.auth.backends.ModelBackend'):
raise forms.ValidationError("Invalid LOGIN")
models.py
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class SignUpManager(BaseUserManager):
def create_user(self, email,age,name, username, password=None):
#if not email:
#raise ValueError("insert user")
if not username:
raise ValueError("insert username")
if not name:
raise ValueError("insert name")
if not age:
raise ValueError("insert age")
user = self.model(
email=self.normalize_email(email),
username=username,
age=age,
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,name,age,username, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
age=age,
name=name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class UserSignupModel(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60,unique=True)
age = models.CharField(max_length=15)
name = models.CharField(max_length=15)
username = models.CharField(max_length=15, unique=True)
date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="last login", auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ['email','name','age']
objects = SignUpManager()
def __str__(self):
return self.name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
#migrate --run-syncdb in case no work
views.py
from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate,logout
from diabetes.forms import UserSignupForm,UserLoginForm
# Create your views here.
def home(request):
return render(request,'diabetes/home.html')
def signupuser(request):
context={}
if request.POST:
form=UserSignupForm(request.POST)
if form.is_valid():
form.save()
email=form.cleaned_data.get('email')
raw_password=form.cleaned_data.get('password1')
name=form.cleaned_data.get('name')
age=form.cleaned_data.get('age')
username=form.cleaned_data.get('username')
account=authenticate(email=email,password=raw_password,name=name,age=age,username=username)
login(request,account)
return redirect('home')
else:
context["reg_form"]=form
else:
form = UserSignupForm()
context["reg_form"] = form
return render (request,'diabetes/signupuser.html',context)
def logoutuser(request):
logout(request)
return redirect('home')
def loginuser(request):
context={}
user=request.user
if user.is_authenticated:
return redirect('home')
if request.method=="POST":
form=UserLoginForm(request.POST)
if form.is_valid():
email=request.POST['email']
password=request.POST['password']
user=authenticate(password=password,email=email,backend='django.contrib.auth.backends.ModelBackend')
if user:
login(request,user)
return redirect("home")
else:
form=UserLoginForm()
context['form']=form
return render(request,"diabetes/loginuser.html",context)
I'm new in Django. I tried to make a registration with a custom user and I'm struggling with errors.
views.py
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from django.views.generic import FormView,TemplateView,ListView
from .forms import RegisterForm
from .models import User
# Create your views here.
#user-login view
def register(request):
registred=False
if request.method=="POST":
user_register=RegisterForm(data=request.POST)
if user_register.is_valid():
user=User.save()
user.set_password(user.password)
user.save()
registred=True
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse('there is a problem')
else:
return render(request,'register.html',{'registred':registred,'user_register':RegisterForm})
def user_login(request):
if request.method=='POST':
email=request.POST.get('email')
password=request.POST.get('password')
user=authenticate(email=email,password=password)
if user is not None:
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account not found")
else:
return render(request,'login.html')
#user-logout view
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
#registration view
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
# accounts.models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
# hook in the New Manager to our Model
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username=models.CharField(default='',unique=True,max_length=50)
full_name=models.CharField(default='',max_length=50)
short_name=models.CharField(default='',max_length=50)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that is built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return self.full_name
def get_short_name(self):
# The user is identified by their email address
return self.short_name
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
#property
def is_active(self):
"Is the user active?"
return self.active
objects = UserManager()
the error :
TypeError at /register/
save() missing 1 required positional argument: 'self'
From views.py, remove user=User.save(), which is invalid not having an instance (that self which is missing)
user_register=RegisterForm(data=request.POST)
if user_register.is_valid():
user = User()
user.set_password(user.password)
user.save()
registred=True
So I'm making a custom user model. This is what I'am following Here. I have been pretty much following the tutorial but still I cant make it done.
Error: RegisterForm() missing 1 required positional argument: 'request'.
here's my code.
forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class UserAdminCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class LoginForm(forms.ModelForm):
email = forms.EmailField(label='Email')
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'password',)
widgets = {
'email' : forms.EmailInput(
attrs={'class':'form-control', 'place_holder': '', }),
'password' : forms.PasswordInput(
attrs={'class':'form-control' }),
}
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserManager(BaseUserManager):
def create_user(self, email, full_name, password=None, is_staff=False, is_active=True, is_admin=False):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
if not full_name:
raise ValueError('Users must have an full name')
if not password:
raise ValueError('Users must have a password')
user = self.model(
email=self.normalize_email(email),
)
user.full_name = full_name
user.set_password(password)
user.staff = is_staff
user.admin = is_admin
user.active = is_active
user.save(using=self._db)
return user
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, full_name, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.model(
email=self.normalize_email(email)
)
user.full_name = full_name
user.set_password(password)
user.full_name = full_name
user.staff = True
user.admin = True
user.save(using=self._db)
return user
# Create your models here.
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, null=True, blank=True)
active = models.BooleanField(default=True) # to login
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
created_date = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name'] # Email & Password are required by default.
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
#property
def is_active(self):
"Is the user active?"
return self.active
class Account_type(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
account_type = models.ForeignKey(Account_type, on_delete=models.CASCADE)
register.html
from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm
# Create your views here.
def RegisterForm(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
else:
form = RegisterForm()
context = {
'form' : form
}
return render(request, 'account/register.html', context)
The view logic is simple as you can see. Just saving up the request into the database. The tutorial itself did not tell anything about the view for login and register.
So, What am I doing wrong here.
Thank you
The problem is that your view RegisterForm has the same name as your form, hence if you call RegisterForm in your view, it will resolve to the view function, and make a recursive call.
Normally (top-level) functions are written in snake_case, hence you can rewrite it to register_form, or even better register (since it is not a form at all):
from django.shortcuts import render, redirect
from . forms import RegisterForm, LoginForm
# Create your views here.
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('some-view-name')
else:
form = RegisterForm()
context = {
'form' : form
}
return render(request, 'account/register.html', context)
Normally a successful POST request results in a redirect to implement the Post/Redirect/Get pattern [wiki]. So I strongly advise you to use redirect(..) [Django-doc] and replace some-view-name with the name of a view to which you want to redirect.
I am new to Django, trying to create a custom user for my project. When I am running the server, it raises No module named 'django.contrib.customuser' and sometimes, Manager isn't available; auth.User has been swapped for Mysite.CustomUser. Even i changed my settings: django.contrib.auth to django.contrib.custommuser. Please someone help me solving this. Here's my code
models.py:
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User, BaseUserManager, AbstractUser, AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
def _create_user(self, username, email, u, password, is_staff, is_active, **extra_fields):
now = datetime.now()
if not email:
raise ValueError('Users must have an email address')
email = self.normalize_email(email)
user = self.model(username=username, email=email, u=u, password=password,
is_staff=is_staff, is_active=False, last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, u, password = None, **extra_fields):
return self._create_user(username, email, u, False, False, **extra_fields)
def create_superuser(self, username, email, u, password = None):
user = self._create_user(username, email, u, password, True, True)
user.set_password(password)
user.is_active=True
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=30)
email = models.EmailField(max_length=30, unique=True, db_index=True)
password1 = models.CharField(max_length=30)
password2 = models.CharField(max_length=30)
CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
u = models.CharField(choices=CHOICES, max_length=20, default=0)
date_joined = models.DateTimeField(_('date joined'), default=datetime.now)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
REQUIRED_FIELDS = ('username', 'u')
USERNAME_FIELD = 'email'
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
return self.is_admin
forms.py
from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import CustomUser#, LinkedInUser, FacebookUser
import re
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
class CustomUserForm(forms.ModelForm):
username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
u = forms.ChoiceField(choices=CHOICES, label='ID', widget=forms.RadioSelect())
class Meta :
model = CustomUser
fields = [ 'username', 'email', 'password1', 'password2', 'u' ]
User = get_user_model()
def clean_name(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("The username already exists. Please try another one."))
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and
password.
"""
def __init__(self, *args, **kargs):
super(CustomUserCreationForm, self).__init__(*args, **kargs)
del self.fields['username']
class Meta:
model = CustomUser
fields = ("email",)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from .models import CustomUser
from .forms import CustomUserCreationForm
class CustomUserAdmin(admin.ModelAdmin):
form = CustomUserCreationForm
admin.site.register(CustomUser, CustomUserAdmin)
backends.py:
from models import CustomUser
class CustomUserAuth(object):
def authenticate(self, username=None, password=None):
try:
user = CustomUser.objects.get(email=username)
if user.check_password(password):
return user
except CustomUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = CustomUser.objects.get(pk=user_id)
if user.is_active:
return user
return None
except CustomUser.DoesNotExist:
return None
Remove django.contrib.customuser and django.contrib.auth from your INSTALLED_APPS. There is no customuser application under django.contrib package, and auth can be omitted (to avoid potential name colission).
Furthermore, I suggest you re-read the Django docs on auth customization. Most of the changes are optional, and your code should be simplified by re-using the base classes, unless your methods vary of course.
The docs also mentions that for swapping User models, you are required to update settings to AUTH_USER_MODEL = 'customuser.CustomUser'.