django custom user model user creation issue: permissions not working - python

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.

Related

How to populate DB from Facebook response using python-social-auth

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?

django custom user model form widgets working only for email and name field

in my custom user model that is created with AbstractBaseUser when i try to add widgets which lets me add classes or place holders or input type etc.. it works only for the full_name and email fields but not for password1 and password2
in my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.conf import settings
class MyAccountManager(BaseUserManager):
def create_user(self, email, full_name, password=None):
if not email:
raise ValueError('Users must have an email address')
if not full_name:
raise ValueError('Users must have a name')
user = self.model(
email=self.normalize_email(email),
full_name=full_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, full_name, password):
user = self.create_user(
email=self.normalize_email(email),
full_name=full_name,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(verbose_name="Email",max_length=250, unique=True)
username = models.CharField(max_length=30, unique=True, null=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)
full_name = models.CharField(verbose_name="Full name", max_length=150, null=True)
profile_pic = models.ImageField(null=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
objects = MyAccountManager()
def __str__(self):
return self.full_name
# For checking permissions.
def has_perm(self, perm, obj=None):
return self.is_admin
# For which users are able to view the app (everyone is)
def has_module_perms(self, app_label):
return True
#i also have another text model which i don't think that is needed
in my forms.py
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate
from .models import *
class TextForm(ModelForm):
class Meta:
model = Text
fields = ['title','document','requirements','deadline']
widgets = {
'title' : forms.TextInput(attrs={'placeholder':'Title','class':'form-control m-2 mb-4 pb-2'}),
'deadline' : forms.DateInput(attrs={'placeholder':'Deadline','type':'date','class':'form-control m-2 pt-2',
'id':'opendate'}),
'requirements' : forms.Textarea(attrs={'placeholder':'requirements','class':'form-control col m-2','rows':'3'}),
'document' : forms.Textarea(attrs={'placeholder':'document','class':'form-control'}),
}
class SignupForm(UserCreationForm):
class Meta:
model = User
fields = ("full_name","email","password1","password2")
widgets = {
'full_name' : forms.TextInput(attrs={'placeholder':'Full name'}),
'email' : forms.EmailInput(attrs={'placeholder':'Email'}),
'password1' : forms.PasswordInput(attrs={'placeholder':'Password'}),
'password2' : forms.PasswordInput(attrs={'placeholder':'Password2'}),
}
class SigninForm(forms.ModelForm):
class Meta:
model = User
fields = ('email','password')
widgets = {
'email' : forms.EmailInput(attrs={'placeholder':'Email','class':'form-control'}),
'password' : forms.PasswordInput(attrs={'placeholder':'Password','class':'form-control'}),
}
def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email,password=password):
raise forms.ValidationError("Invalid login")
in my view.py file
def home(request):
user = request.user
# for creating posts
form = TextForm()
if request.method == "POST":
form = TextForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
author = User.objects.filter(email=user.email).first()
obj.author = author
form.save()
form = TextForm()
texts = Text.objects.all().order_by('-id')
# for signing in
if request.POST:
signin_form = SigninForm(request.POST)
if signin_form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
else:
signin_form = SigninForm()
# for signing up
signup_form = SignupForm()
if request.method == 'POST':
signup_form = SignupForm(request.POST)
if signup_form.is_valid():
User = signup_form.save()
full_name = signup_form.cleaned_data.get('full_name')
email = signup_form.cleaned_data.get('email')
raw_password = signup_form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
context = {'signin_form':signin_form,'signup_form':signup_form,'form': form, 'texts': texts}
return render(request, 'main/home.html', context)
NB: in the template i rendred them one by one like: {{signup_form.full_name}} , {{signup_form.password1}} etc... and it's working fine in terms of the backend

adding required files to custom user when registration in django

I’m really new in Django and I would like to create a register form to login user.
I would like this form have additional and required fields. the problem is when I try to fill the sign up registration directly on the web, the user is not registered, but if I do it in /admin section, the user is saved, so I have used custom user
So first I have created class in model.py file:
class Account (AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, 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)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(
validators=[phone_regex], max_length=17, blank=True) # validators should be a list
role = models.CharField(max_length=50)
store = models.CharField(max_length=50)
aisle = models.CharField(max_length=50, unique=True)
user_identification = models.CharField(max_length=30, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name',
'phone_number', 'role', 'store', 'aisle', 'user_identification']
objects = MyAccountManager()
def __str__(self):
return self.email
# if user is admin, can chenge
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
#property
def staff(self):
return self.is_staff
#property
def active(self):
return self.is_active
after I have created the Account Manager in the same models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name,
phone_number, role, store, aisle, user_identification, password=None):
if not email:
raise ValueError("Users must have an email address")
if not username:
raise ValueError("Users must have an user name")
if not first_name:
raise ValueError("Users must have an user name")
if not last_name:
raise ValueError("Users must have an user name")
if not phone_number:
raise ValueError("Users must have an user name")
if not role:
raise ValueError("Users must have an user name")
if not store:
raise ValueError("Users must have an user name")
if not aisle:
raise ValueError("Users must have an user name")
if not user_identification:
raise ValueError("Users must have an user name")
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
role=role,
store=store,
aisle=aisle,
user_identification=user_identification,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, first_name, last_name,
phone_number, role, store, aisle, user_identification, password=None):
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
role=role,
store=store,
aisle=aisle,
user_identification=user_identification,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
then in the forms.py file I have created the register method:
class RegistrationForm(UserCreationForm):
email = forms.EmailField(
max_length=60, help_text='Required. Add a valid email address')
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
phone_number = forms.CharField(max_length=30)
role = forms.CharField(max_length=30)
aisle = forms.CharField(max_length=30)
user_identification = forms.CharField(max_length=30)
class Meta:
model = Account
fields = ["email", "username", "password1", "password2", 'first_name', 'last_name',
'phone_number', 'role', 'store', 'aisle', 'user_identification', ]
def clean_password2(self):
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):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.phone_number = self.cleaned_data['phone_number']
user.role = self.cleaned_data['role']
user.aisle = self.cleaned_data['aisle']
user.user_identification = self.cleaned_data['user_identification']
if commit:
user.save()
return user
and the view looks like that:
def registration_view(request): # request, GET from the web
form = RegistrationForm()
context = {}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
# name = form.cleaned_data.get('email')
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
# here we inflate and return the view
return render(request, 'account/register.html', context)
I have configured in settings.py the user custom model:
AUTH_USER_MODEL = 'account.Account'
Also I have configured the admin.py file
class AccountAdmin (UserAdmin):
list_display = ('email', 'username', 'date_joined',
'last_login', 'is_admin', 'is_staff',)
search_fields = ('email', 'username',)
readonly_fields = ('date_joined', 'last_login')
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(Account, AccountAdmin)
admin.site.register(UserProfile)
thanks a lot for your help guys!
Perhaps are you always setting commit=false in order to work with it before saving, but then always is going to avoid saving because the if sentence at the end of the Def ?
class RegistrationForm(UserCreationForm):
...
def save(self, commit=True):
user = super(RegistrationForm, self).save(**commit=False**)
user.set_password(self.cleaned_data["password1"])
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.phone_number = self.cleaned_data['phone_number']
user.role = self.cleaned_data['role']
user.aisle = self.cleaned_data['aisle']
user.user_identification = self.cleaned_data['user_identification']
**if commit:**
user.save()
return user
I hope this helps!

Django custom user model : User creation issue

I am have created a custom user model to replace username with email. But when I am trying to add user from Django Admin I get error:
Please correct the errors below.
There is no other information with that error message.
The code for custom user:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name="email_address",
max_length=255,
unique=True,
)
name = models.CharField(max_length=255)
is_staff = models.BooleanField(
default=False,
)
is_active = models.BooleanField(
default=True,
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
return self.name
def __str__(self):
return self.email
Custom User Manager Code:
class UserManager(BaseUserManager):
def _create_user(self, email, password, **kwargs):
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
return user
def create_user(self, email, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **kwargs):
kwargs.setdefault('is_staff', True)
kwargs.setdefault('is_superuser', True)
kwargs.setdefault('is_active', True)
if kwargs.get('is_staff') is not True:
raise ValueError("Superuser must have is_staff True")
if kwargs.get('is_superuser') is not True:
raise ValueError("Superuser must have is_superuser True")
return self._create_user(email, password, **kwargs)
and the admin code for same:
class CustomUserAdmin(BaseUserAdmin):
add_form = CustomUserCreationForm
form = CustomUserCreationForm
list_display = ('id', 'email', 'is_superuser')
list_filter = ('is_superuser',)
fieldsets = (
(None, {'fields': ('name', 'email', 'password')}),
('Permissions', {'fields': ('is_superuser', 'is_staff')}),
)
add_fieldsets = fieldsets
search_fields = ('name', 'email')
ordering = ('name', 'email')
filter_horizontal = ()
Custom User Form:
# users/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import User
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('name', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('name', 'email')
I have tried many changes but couldn't figure out the issue. I would appreciate any help on this.
Change:
class Meta:
model = User
fields = ('name', 'email')
To:
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('name', 'email')

How to eliminate username from authentication

I want to eliminate the concept of a username from the django auth in my app. I want the email of the user to take place of the username. So I extended AbstractBaseUser with the code below
class AuthUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("Users must have an email address")
user = self.model(email=self.normalize_email(email),)
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email=email, password=password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class AuthUser(AbstractBaseUser, PermissionsMixin):
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message = "Only alphanumeric characters are allowed")
email = models.EmailField(verbose_name='email address',unique=True, max_length=255)
first_name = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
last_name = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True, null=False)
is_staff = models.BooleanField(default=False, null=False)
#custom fields
company_name = models.CharField(max_length=100)
telephone_number = models.CharField(max_length=100)
website_url = models.CharField(max_length=100)
objects = AuthUserManager()
USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['first_name']
def get_full_name(self):
fullname = self.first_name + self.last_name
return fullname
def get_short_name(self):
return self.email
def __unicode__(self):
return self.email
In my serializers.py I have this
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = AuthUser
fields = ('email', 'first_name', 'last_name')
def create(self, validated_data):
user = AuthUser.objects.create(**validated_data)
return user
def update(self, instance, validated_data):
instance.email = validated_data.get('email', instance.email)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.save()
return instance
But when I try to register I get the following error:
{
"username": [
"This field is required."
]
}
What am I doing wrong?
In your serializer, you need to exclude username field, because you are inheriting from AbstractBaseUser and you still have 'username' field, so add this exclude = ('username',)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = AuthUser
fields = ('email', 'first_name', 'last_name')
exclude = ('username',)
def create(self, validated_data):
user = AuthUser.objects.create(**validated_data)
return user

Categories