I have Django with python-social-auth installed.
My custom user model:
class User(AbstractUser):
"""Custom User model."""
username = None
email = models.EmailField(blank=False, unique=True, verbose_name=_("Email"))
facebook_link = models.URLField(blank=True, verbose_name=_("Facebook profile link"))
contacts = models.CharField(blank=True, max_length=250, verbose_name=_("Contacts"))
hometown = models.CharField(blank=True, max_length=250, verbose_name=_("Hometown"))
start_coordinates = models.CharField(blank=True, max_length=100, verbose_name=_("Start coordinates"))
avatar = ProcessedImageField(
upload_to="avatar/",
format="JPEG",
options={"quality": 80},
default="avatar/default_avatar.jpg",
verbose_name=_("Image"),
)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
def __str__(self):
"""Model representation."""
return self.email
def get_absolute_url(self):
"""Get url to User's model instance."""
return reverse_lazy("public-profile", kwargs={"user_id": self.pk})
def get_full_name(self):
"""Concatenate fist and last names."""
full_name = " ".join([self.first_name, self.last_name])
return full_name.strip()
get_full_name.short_description = _("Full name")
class Meta:
verbose_name = _("User")
verbose_name_plural = _("Users")
Managers.py
class UserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password=None, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError(_("Email required"))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and password."""
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
extra_fields.setdefault("is_active", True)
if extra_fields.get("is_staff") is not True:
raise ValueError(_("Superuser must have is_staff=True."))
if extra_fields.get("is_superuser") is not True:
raise ValueError(_("Superuser must have is_superuser=True."))
return self.create_user(email, password, **extra_fields)
I do succesfull authentication with Facebook with this code:
AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_USER_MODEL = 'accounts.User'
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'home'
SOCIAL_AUTH_LOGIN_URL = 'login'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link', 'user_hometown']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
'fields': 'id, name, email, picture.type(large), link, hometown'
}
SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [
('name', 'name'),
('email', 'email'),
('picture', 'avatar'),
('link', 'facebook_link'),
('hometown', 'hometown'),
]
As a result, I have a new user instance created in DB with the automatically populated fields:
fist_name, last_name, email.
How do I can populate the rest of fields (facebook_link, hometown) with data from response?
Related
i have a custom user model and i want to create a superuser from a view right, am currently using django restframework, below is my custom model and serializer with the views.
model.py
class CompanyUserManager(UserManager):
def _create_user(self, username, email, password, **extra_fields):
"""
Create and save a user with the given username, email and passsword
"""
if not username:
raise ValueError('The given username must be set')
if not email:
raise ValueError('The email must be set')
email = self.normalize_email(email)
username = self.model.normalize_username(username)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username: str, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, email, password, **extra_fields)
def create_admin_user(self, username: str, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_admin', True)
# if extra_fields.get('is_staff') is not True:
# raise ValueError('Super user must have is_staff=True')
# if extra_fields.get('is_admin') is not True:
# raise ValueError('Super user must have is_admin=True')
# if extra_fields.get('is_superuser') is True:
# raise ValueError('Superuser must have is_superuser=False')
return self._create_user(username, email, password, **extra_fields)
def create_superuser(self, username: str, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_admin', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Super user must have is_staff=True')
if extra_fields.get('is_admin') is not True:
raise ValueError('Super user must have is_admin=True')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True')
return self._create_user(username, email, password, **extra_fields)
# Create your models here.
class CompanyUser(AbstractBaseUser, PermissionsMixin):
username_validator = UnicodeUsernameValidator()
username = models.CharField(_('username'), max_length=150, unique=True, help_text='Required, 150 characters or fewer', error_messages={'unique ': ' a User with this user name is already registered'}, validators=[username_validator])
email = models.EmailField(_('email address'), blank=False, unique=True)
phone = models.CharField(_('phone'), max_length=20, blank=True, null=True)
is_staff = models.BooleanField(_('staff status'), default=True, help_text='Designated user can login using this account')
is_active = models.BooleanField(_('active'), default=True, help_text='Designated whether this user should be treated as active')
is_superuser = models.BooleanField(_('superuser'), default=False, help_text='Designated user can login using this account')
is_admin = models.BooleanField(_('admin'), default=False, help_text='Designated user can login using this account')
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
email_verified = models.BooleanField(_('email_verified'), default=False,)
objects = CompanyUserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD: str = 'email'
REQUIRED_FIELDS = ['username', 'phone']
#property
def token(self):
token = jwt.encode({
'username': self.username,
'email': self.email,
'exp': datetime.utcnow() + timedelta(hours=24)},
settings.SECRET_KEY, algorithm='HS256')
return token
#property
def staff(self):
return self.is_staff
#property
def admin(self):
return self.is_admin
#property
def active(self):
return self.is_active
#property
def owner(self):
return self.is_superuser
serializer.py
class RegisterSerializer(serializers.ModelSerializer):
# username = serializers.CharField(max_length=100)
# email = serializers.EmailField()
# password = serializers.CharField(max_length=100)
# password2 = serializers.CharField(max_length=100)
# def validate(self, data):
# if data['password'] != data['password2']:
# raise serializers.ValidationError('Passwords must match')
# return data
password = serializers.CharField(max_length=100, write_only=True)
class Meta:
model = CompanyUser
fields = ("id", "username", "email", "password", "is_active")
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
user = CompanyUser(**validated_data)
user.set_password(validated_data["password"])
user.save()
return user
def create_superuser(self, validated_data):
user = CompanyUser(**validated_data)
print(validated_data)
if "password" in validated_data:
from django.contrib.auth.hashers import make_password
validated_data["password"] = make_password(validated_data["password"])
user.set_password(validated_data["password"])
user.is_superuser = True
user.is_admin = True
user.is_staff = True
user.save()
return user
the create_superuser isnt working, it throws a keyerror password not found
view.py
class RegisterAPIView(GenericAPIView):
"""
A view that allow company owners to create an account
"""
serializer_class = RegisterSerializer
def post(self, request, *args, **kwargs):
serializers = self.serializer_class(data=request.data)
if serializers.is_valid():
serializers.save()
# self.serializer_class.create_superuser(serializers.data)
# serializers.create_superuser(serializers.data)
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
so this are my codes and i cant create a superuser from the endpoint, i dont want to use the django cli, any help please 😌
I've been on dj_rest_auth on this project. Trying to add extra fields to the custom user model but it only saves the email and password. I think I have everything right but nothings working.
Heres my user model
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError('The Email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
username = None
email = models.EmailField('email address', unique=True)
USERNAME_FIELD = 'email'
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
phone = models.CharField(max_length=30, blank=True)
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
serializers.py
class UserSerializer(serializers.ModelSerializer):
phone = serializers.CharField(max_length=30, allow_blank=True)
first_name = serializers.CharField(max_length=30, allow_blank=True)
last_name = serializers.CharField(max_length=30, allow_blank=True)
class Meta:
model = CustomUser
fields = ('id', 'email', 'first_name', 'last_name', 'phone')
def save(self, request):
user = super().save(request)
user.phone = self.data.get('phone')
user.first_name = self.data.get('first_name')
user.last_name = self.data.get('last_name')
user.save()
return user
settings.py
AUTH_USER_MODEL = 'users.CustomUser'
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'users.serializers.UserSerializer',
}
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
and finally in my urls.py
path('register/', RegisterView.as_view()),
From postman I send this post request
{
"email": "ahsan44411#gmail.com",
"password": "ahsan44411",
"password2": "ahsan44411",
"first_name": "ahsan",
"last_name": "mukhtar",
"phone": "64763868"
}
It only saves the email address, phone, first_name, last_name are not saved.
I have searched read nearly every problem on stackoverflow, without any luck, now I am posting here, please inform me if problem is not clear.
You can use the create function to save user data like this. Hope this answer will help you to solve your problem.
def create(self, data):
u = User(username=data["username"], email=data["email"],phone=data["phone"], first_name=data["first_name"],last_name=data["first_name"])
u.set_password(data["password"])
u.save()
return u
I'm making a custom user model in django, but somehow any new users created through the creation form is missing their assigned permissions (is_active, is_staff, is_admin), preventing them from logging in at all.
Can anyone show me where did I go wrong? Any suggestion is greatly appreciated!
Code snippets:
models.py
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, ID, name, email, privilege, password=None):
if not ID:
raise ValueError('Users must have a ID number')
user = self.model(
ID=ID,
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
if self.privilege == 'Admin':
self.is_superuser = True
else:
user.is_active = True
user.is_staff = False
user.is_admin = False
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, NIP, name, email, privilege, password):
new_user = self.create_user(
ID,
name,
email,
privilege,
password=password,
)
new_user.is_superuser = True
new_user.save(using=self._db)
return new_user
class employee(AbstractBaseUser, PermissionsMixin):
ID = models.IntegerField(verbose_name="ID", unique=True)
name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True)
email = models.EmailField(verbose_name="email", max_length=225, default='this#mail.com')
Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='')
Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='')
privilege = models.CharField(max_length=10, default='User')
is_admin = models.BooleanField()
is_staff = models.BooleanField()
is_active = models.BooleanField()
forms.py
class CustomUserCreationForm(UserCreationForm):
ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta(UserCreationForm):
model = employee
fields = "__all__"
class CustomUserChangeForm(UserChangeForm):
ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = employee
fields = "__all__"
admin.py
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
add_form = CustomUserChangeForm
form = CustomUserChangeForm
model = employee
list_display = ('ID', 'name', 'email', 'privilege')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('ID', 'password')}),
('Personal info', {'fields': ('name', 'email', 'privilege')}),
('Permissions', {'fields': ('is_admin', 'is_staff', 'is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('ID', 'name', 'email')}
),
)
search_fields = ('name',)
ordering = ('ID',)
filter_horizontal = ()
views.py
def employee_list(request):
data_list = Employee.objects.order_by('NIP')
registered = False
if request.method == "POST":
if 'add_user' in request.POST:
user_form = CustomUserCreationForm(request.POST, prefix='add')
if user_form.is_valid():
new_user = user_form.save()
new_user.set_password(user.password)
new_user.save()
registered = True
return HttpResponseRedirect(reverse('employee'))
else:
user_form = CustomUserCreationForm(prefix='add')
return render(request, 'employee_list.html',
{'SignUpForm': user_form,
'registered': registered,
'Emp_list':data_list})
Instead of using 'priviledge' as a character field in the Employee model, which is very prone to error in user input, use a choice field instead.
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
user.set_password(password)
user.is_active = True
user.is_staff = is_staff
user.is_admin = is_admin
user.save(using=self._db)
return user
def create_superuser(self, name, email, password):
new_user = self.create_user(
name,
email,
privilege='admin',
password=password,
is_staff=True,
is_admin=True
)
return new_user
class Employee(AbstractBaseUser):
PRIVILEGE_LEVEL = (
('Administrator', 'admin'),
('Staff', 'staff'),
('Member', 'member'),
)
# ID = models.IntegerField(verbose_name="ID", unique=True)
id = models.AutoField(primary_key=True)
name = models.CharField(verbose_name="Name", max_length=50, blank=True, unique=True)
email = models.EmailField(verbose_name="email", max_length=225, default='this#mail.com')
Department = models.CharField(max_length=50, choices=DEP_CHOICES, default='')
Role = models.CharField(max_length=50, choices=ROLE_CHOICES, default='')
# privilege = models.CharField(max_length=10, default='User')
privilege = models.CharField(max_length=120, choices=PRIVILEGE_LEVEL, default='member')
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
Also, 'id' is auto generated by django as the primary key field, so it doesnt have to be in the frontend form.
By default the django model form calls MyUserManager.create_user.
and based on the modifications i made above, it defaults to creating a user
without permissions. Unless is_admin and is_staff are implicitly set to True
To create a superuser from your current form, you can update MyUserManager.create_user like so,
def create_user(self, name, email, privilege='member', is_admin=False, is_staff=False, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
name=name,
email=self.normalize_email(email),
privilege=privilege,
)
user.set_password(password)
user.is_active = True
user.is_staff = is_staff
user.is_admin = is_admin
if privilege == 'admin':
user.is_superuser = True
user.save(using=self._db)
return user
But i would advise you update your CustomUserCreationForm instead as such,
class CustomUserCreationForm(UserCreationForm):
# ID = forms.CharField(max_length=50)
password = forms.CharField(widget=forms.PasswordInput)
class Meta(UserCreationForm):
model = Employee
fields = "__all__"
# ADD THIS
def clean(self, value):
print(self.data)
print(self.errors)
cleaned_data = self.cleaned_data
print(cleaned_data)
return cleaned_data
# ADD THIS
def save(self, *args, **kwargs):
data = self.cleaned_data
# email, password1 = v['email'], v['password1']
employee = None
if data['privilege'] == 'admin':
employee = Employee.objects.create_superuser(
name=data['name'],
email=data['email'],
password=data['password'],
)
else:
employee = Employee.objects.create_user(
name=data['name'],
email=data['email'],
password=data['password'],
)
# User is already saved after calling BaseUserManager function.
return employee
MyUserManager.create_superuser calls the MyUserManager.create_user and updates it based on parameter passed to it.
Let me know if you need further clarifications. Cheers.
I am using Django user model and also extended with my own profile model for some other data.When i want to update user data which is in Profile Model It doesn't get updated because all the user id,username,email,password reside in user model while the fields which are needed to get updated are in profile model.I have used this approach, all it does is takes inputs and displays the response but does not show any change in User Data when viewing it as a whole.
models.py
class Profile(models.Model):
user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE)
location = models.CharField(max_length=30,blank=True)
friends_count = models.PositiveIntegerField(default=0)
profile_pic = models.FileField(upload_to='profile_pics/',blank=True,null=True)
def natural_key(self):
return (self.user.username,)
views.py
class UserCreateAPIViewSet(viewsets.ModelViewSet,mixins.UpdateModelMixin):
""""A View which handles Creating and Updating User Profile"""
serializer_class = UserProfileCreateSerializer
queryset = User.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnProfile,)
filter_backends = (filters.SearchFilter,)
search_fields = ('username','email',)
class UserUpdateAPI(generics.GenericAPIView,mixins.UpdateModelMixin):
"""Update User Profile Data"""
permission_classes = (permissions.UpdateOwnProfile,)
authentication_classes = (TokenAuthentication,)
queryset = Profile.objects.all()
serializer_class = ProfileUpdateSerializer
def put(self,request,*args,**kwargs):
return self.partial_update(request,*args,**kwargs)
urls.py
url(r'^user-update/(?P<pk>\d+)/$',views.UserUpdateAPI.as_view(),name="user-update"),
router = DefaultRouter()
router.register(r'profile',views.UserCreateAPIViewSet)
serializers.py
class UserProfileCreateSerializer(serializers.ModelSerializer):
""""A serializer for user data request"""
location = serializers.CharField(source='profile.location')
friends_count = serializers.IntegerField(source='profile.friends_count',read_only=True)
profile_pic = serializers.FileField(source='profile.profile_pic',allow_empty_file=True,allow_null=True)
class Meta:
model = User
fields = (
'pk',
'username',
'email',
'password',
'location',
'friends_count',
'profile_pic',
)
extra_kwargs = {
'password':{'write_only':True},
'friends_count':{'read_only':True},
}
def create(self, validated_data):
""""Create and return a new User"""
user = User(
email = validated_data['email'],
username = validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class ProfileUpdateSerializer(serializers.ModelSerializer):
"""A serializer for updating user data"""
class Meta:
model = Profile
fields = ('location','profile_pic')
Looks like you want to extend from the AbstractBaseUser (see code below), using this as your UserProfileCreateSerializer:
class UserProfileCreateSerializer(serializers.ModelSerializer):
""""A serializer for user data request"""
location = serializers.CharField(source='profile.location')
friends_count = serializers.IntegerField(source='profile.friends_count',read_only=True)
profile_pic = serializers.FileField(source='profile.profile_pic',allow_empty_file=True,allow_null=True)
class Meta:
model = Profile
fields = (
'pk',
'username',
'email',
'password',
'location',
'friends_count',
'profile_pic',
)
extra_kwargs = {
'password':{'write_only':True},
'friends_count':{'read_only':True},
}
def create(self, validated_data):
""""Create and return a new User"""
user = Profile(
email = validated_data['email'],
username = validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class ProfileUpdateSerializer(serializers.ModelSerializer):
"""A serializer for updating user data"""
class Meta:
model = Profile
fields = ('location','profile_pic')
Then extend from the AbstractBaseUser in models.py:
from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from .managers import ProfileManager
class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(_('first name'), max_length=30, blank=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
is_active = models.BooleanField(_('active'), default=True)
location = models.CharField(max_length=30,blank=True)
friends_count = models.PositiveIntegerField(default=0)
profile_pic = models.FileField(upload_to='profile_pics/',blank=True,null=True)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
'''
Returns the short name for the user.
'''
return self.first_name
def natural_key(self):
return (self.username,)
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this User.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
And then create a file called managers.py in the same directory as models.py:
from django.contrib.auth.base_user import BaseUserManager
class ProfileManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
To wrap all this up you need to add this to your settings.py file:
AUTH_USER_MODEL = 'app.Profile'
And also don't forget to re-run all database migrations before using $ python manage.py runserver.
I created a custom user model for my Django project so that the user could login in with their email. However, the authentication wouldn't work.
Here is my code:
Views:
def login_view(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
user = authenticate(usename=email, password=password)
if user:
print(True)
login(request, user)
return redirect('/account/')
else:
print(str(password)+" "+str(email))
print(False)
else:
form = LoginForm()
return render(request, 'users/login.html',{'form': form})
my backend:
def authenticate(self, username=None, password=None,):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return True
except User.DoesNotExist:
return True
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
My User Model:
class UserManager(BaseUserManager):
def _create_user(self, first_name, last_name, username, email, is_admin, password=None, **extra_fields):
"""
creates a User with first name, last name, username, email, password
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
first_name=first_name,
last_name=last_name,
username=username,
email=email,
is_admin=is_admin,
is_active=True,
**extra_fields,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, first_name, last_name, username, email, password, **extra_fields):
return self._create_user(
first_name,
last_name,
username,
email,
False,
password,
**extra_fields
)
def create_superuser(self, first_name, last_name, username, email, password=None, **extra_fields):
return self._create_user(
first_name,
last_name,
username,
email,
True,
password,
**extra_fields
)
class User(AbstractBaseUser):
first_name = models.CharField(
max_length=256,
unique=False,
verbose_name='first name',
)
last_name = models.CharField(
verbose_name='last name',
max_length=256,
unique=False,
)
username = models.CharField(
verbose_name='username',
max_length=256,
unique=False,
)
email = models.EmailField(
verbose_name='email',
max_length=256,
unique=True,
)
is_active = models.BooleanField(
default=True,
)
is_admin = models.BooleanField(
default=False,
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [
'first_name',
'last_name',
'username',
]
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = "{} {}".format(self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def __str__(self): # __unicode__ on Python 2
return self.email
def email_user(self, subject, message, from_email):
send_mail(subject, message, from_email, [self.email])
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
def has_perm(self, perm, obj=None):
return self.is_admin
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
My settings:
AUTH_USER_MODEL = 'custom_user.User'
AUTHENTICATION_BACKENDS = ('custom_user.backends.UserAuth', )
My Forms:
email = forms.CharField(
widget=forms.TextInput(attrs={'class': 'registerforms', 'placeholder': 'Email'}),
label='',
)
password = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'registerforms', 'placeholder': 'Password'}),
label='',
)
I do not get an error however it doesn't log the user in