class UserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if username is None:
raise TypeError('User should have a username')
if email is None:
raise TypeError('User should have an email')
user = self.model(
username=username,
email=self.normalize_email(email)
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None):
if password is None:
raise TypeError('Password should not be none')
user = self.create_user(username, email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(
max_length = 255,
unique = True,
db_index = True
)
email = models.EmailField(
max_length = 255,
unique = True,
db_index = True
)
is_verified = models.BooleanField(default = False)
is_staff = models.BooleanField(default = True)
is_active = models.BooleanField(default = True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
def __str__(self):
return self.email
def tokens(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length = 255,
min_length = 6,
write_only = True
)
class Meta:
model = User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not username.isalnum():
raise serializers.ValidationError(
"Username should contain only alphanumeric characters"
)
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
class RegisterView(generics.GenericAPIView):
permission_classes = (AllowAny,)
serializer_class = RegisterSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
return Response(
serializer.data,
status=status.HTTP_201_CREATED
)
Currently I'm using django 3.1.3 and djangorestframework 3.12.2. While I'm able to login with superuser and getting tokens properly but couldn't login with staff users. From Django admin I have seen only superuser has hashed password and all other users have plain text password.
You do not set the password with user.password, that is just a text field on a model and works like any other. You must either:
preferred: Call user.set_password(value)
backup: Calculate the password manually using make_password before saving
You already have a create method so we'll work with that first.
from django.contrib.auth.hashers import make_password
def create(self, validated_data):
pwd = validated_data.pop("password")
user = User.objects.create(**attrs)
user.set_password(pwd)
user.save(updated_fields=["password"])
return user
# or you could replace it in validated_data
def create(self, validated_data):
validated_data["password"] = make_password(validated_data["password"])
return User.objects.create(**attrs)
You have a validation routine, but it is global. If you make it specific to the password field then you can calculate it there and leave create alone. People don't usually do that, because it is standard to have a "confirm password" field as well.
def validate_password(self, value):
# ...
return make_password(value)
Now if you want to add a confirm_password field then you are going to need to a validate(self, attrs) anyway to compare the two fields, so I would recommend against this last method.
Related
I have three different questions. They're all related to each other.
1 - I get an error when I add password2 or confirm_password field.
Got a `TypeError` when calling `CustomUser.objects.create()`.
This may be because you have a writable field on the serializer class that is not a valid argument to `CustomUser.objects.create()`.
You may need to make the field read-only, or override the UserCreateSerializer.create() method to handle this correctly.
TypeError: CustomUser() got an unexpected keyword argument 'confirm_password'
2 - Without any validate when I only have password field. I am not getting any errors but passwords are not hashed.
3 - When I want to create user using shell. Even if I leave all the fields blank, I can create an empty user without any errors.
Custom User Manager
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None,**kwargs):
if not email:
raise ValueError('Email is required!')
user = self.model(
email = self.normalize_email(email),
**kwargs,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **kwargs):
user = self.create_user(
email,
password=password,
**kwargs
)
user.is_admin = True
user.save(using=self._db)
return user
Custom User
class CustomUser(AbstractBaseUser):
email = models.EmailField(_('Email'), max_length=50, unique=True)
username = models.CharField(_('Username'),max_length=50)
first_name = models.CharField(_('First Name'),max_length=50)
middle_name = models.CharField(_('Middle Name'),max_length=50, blank=True, null=True)
last_name = models.CharField(_('Last Name'),max_length=50)
desc = models.TextField(_('Description'), blank=True, default='Nothing here.')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
"Is the user a member of staff?"
return self.is_admin
User Serializer
User = get_user_model()
class UserCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True, validators =[validators.UniqueValidator(queryset=User.objects.all())])
password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
confirm_password = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = [
'email',
'username',
'first_name',
'middle_name',
'last_name',
'password',
'confirm_password',
]
def validate(self, data):
email = data['email']
print(data)
user_qs = User.objects.filter(email=email)
if user_qs.exists():
raise serializers.ValidationError('This user has already registered!')
if data['password'] != data['confirm_password']:
raise serializers.ValidationError('Passwords didn\'t match!')
elif data.get('password') == data.get('confirm_password'):
data['password'] = make_password(
data.get('password')
)
data.pop('confirm_password', None)
return data
def create(self, validated_data):
username = validated_data['username']
email = validated_data['email']
first_name = validated_data['first_name']
middle_name = validated_data['middle_name']
last_name = validated_data['last_name']
user = User.objects.create(
username = username,
email = email,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
)
user.set_password(validated_data['password'])
user.save()
return user
when i am sending post request to register new user from postman, username saves as blank/dash .
why username saving as blank i dont get it.
but when i add from django admin it saves correctly.
here is postman image
postman post request image
and here is the result
django result after sending post request
Custom Account Manager
class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, username, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_active', True)
other_fields.setdefault('is_admin', True)
other_fields.setdefault('is_superuser', True)
if other_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, username, password, **other_fields)
def create_user(self, email, username, password, **other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
if not username:
raise ValueError(_('You must provide an username'))
if " " in username:
raise ValueError(_('Username should not contain space'))
email = self.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save()
return user
Custom User Model
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True, null=False, blank=False)
username = models.CharField(max_length=150, unique=True, null=True)
first_name = models.CharField(max_length=150, blank=True)
objects = CustomAccountManager()
# more
class Meta:
verbose_name = 'NewUser'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return str(self.username)
model serializer
class RegisterNewUserSerializer(serializers.ModelSerializer):
class Meta:
model = NewUser
fields = ('email', 'password', 'username')
extra_kwargs={'password':{'write_only':True}}
def validate(self, data):
if hasattr(self, 'initial_data'):
unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys())
if unknown_keys:
raise ValidationError("Got unknown fields: {}".format(unknown_keys))
return data
def validate_username(self, value):
if " " in value:
raise serializers.ValidationError("Username should not contain space")
def save(self):
newuser = NewUser(email = self.validated_data['email'],
username = self.validated_data['username']
)
password = self.validated_data['password']
newuser.set_password(password)
newuser.save()
return newuser
post request
class RegistrationView(APIView):
permission_classes = [ AllowAny ]
def post(self, request):
reg_serializer = RegisterNewUserSerializer(data = request.data)
print(request.data)
print(reg_serializer)
if reg_serializer.is_valid():
print('lololololololololololo')
reg_serializer.save()
return Response(data=request.data,status=status.HTTP_201_CREATED)
return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
You validator should return the data, so:
def validate_username(self, value):
if " " in value:
raise serializers.ValidationError("Username should not contain space")
# ↓ return the value
return value
In Python a function call always returns something (unless an exception is raised). If no explicit return statement is triggered, None is returned.
I want to create a custom Signup form with Django Rest Auth and Django Allauth but I'm getting an error save() takes 1 positional argument but 2 were given
I know that this error is related to the function def save(self, request) provided by Django Rest Auth, but I have no clue how I can change it.
What should I do to make it work?
Bellow is the respective code for my user Model and Serializer:
# Models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
"""Creates and saves a new super user"""
user = self.create_user(email, password, **extra_fields)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
age = models.PositiveIntegerField(null=True, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'age']
def __str__(self):
return self.email
# serializers.py
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name', 'age')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return it"""
password = validated_data.pop('password', None)
user = super().update(instance, **validated_data)
if password:
user.set_password(password)
user.save()
return user
def save(self, request):
# I would say that I need to change the default function
# settings. py
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'user.serializers.UserSerializer'
}
In order to get this fixed I just add the following to my serializer:
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name', 'age')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return it"""
password = validated_data.pop('password', None)
user = super().update(instance, **validated_data)
if password:
user.set_password(password)
user.save()
return user
def get_cleaned_data(self):
return {
'password': self.validated_data.get('password', ''),
'email': self.validated_data.get('email', ''),
'name': self.validated_data.get('name', ''),
'age': self.validated_data.get('age', ''),
}
def save(self, request):
self.cleaned_data = self.get_cleaned_data()
user = get_user_model().objects.create_user(**self.cleaned_data)
return user
I am trying create user through an API, But i am struck on above error.
Below are the code of the User and its manager. Here, I am creating custom user model.
class UserManager(BaseUserManager):
def create_user(self,username,email, password=None):
if username is None:
raise TypeError('Users should have a Username')
if email is None:
raise TypeError('Users should have a Email')
user = self.model(username=username,email=self.normalize_email)
user.set_password(password)
user.save()
return user
def create_superuser(self,username,email, password=None):
if password is None:
raise TypeError('Password should not be none')
user = self.create_user(username, email, password)
user.save()
return user
class User(AbstractBaseUser,PermissionsMixin):
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.EmailField(max_length=255,unique=True,db_index=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects= UserManager()
def __str__(self):
return self.email
Below is serializers.py file.
class RegisterSerializers(serializers.ModelSerializer):
password = serializers.CharField(max_length=68, min_length=6, write_only=True)
class Meta:
model = User
fields = ['email','username','password']
def validate(self, attrs):
email = attrs.get('email','')
username = attrs.get('username','')
if not username.isalnum():
raise serializers.ValidationError('The username should only contain alphanumeric character')
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
Here is POST request in views.py
class RegisterView(generics.GenericAPIView):
serializer_class = RegisterSerializers
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
return Response(user_data,status=status.HTTP_201_CREATED)
I am new to drf. Kindly help me out, thanks.
I'm making a simple django rest framework project.
This is just creating a new user, and logging in.
When I used django basic auth user model, everything worked well.
But after changing basic user model to custom user, this error comes out when creating a new user:
dict object has no attribute 'pk'
Custom user model is made referred to django docs.
Error says that:
File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/auth/__init__.py",
line 100, in login
if _get_user_session_key(request) != user.pk or ( AttributeError: 'dict' object has no attribute 'pk'
This seems to say that user model has no pk, but I don't get it.
models.py
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have an user name')
user = self.model(
email=self.normalize_email(email),
username = username
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password):
user = self.create_user(
username,
password=password,
email = email,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
id = models.AutoField(primary_key=True)
username = models.CharField(
verbose_name='user name',
max_length=30,
unique=True,
)
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
sth_test = models.TextField(blank = True)
objects = MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
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?"
# Simplest possible answer: All admins are staff
return self.is_admin
serializers.py
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model
fields = ('id', 'username', 'email', 'password', 'is_active')
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
username = serializers.CharField(
max_length=32,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(min_length=8, write_only=True)
def validate_email(self,value):
if User.objects.filter(email=value).exists():
raise serializers.ValidationError("err.")
return value
def create(self, validated_data):
user = User.objects.create_user(
validated_data['username'],
validated_data['email'],
validated_data['password'],
)
user.is_active = False
user.save()
message=render_to_string('accounts/account_activate_email.html',{
'user':user,
'domain':'localhost:8000/api/accounts/activate',
'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode('utf-8'),
'token':account_activation_token.make_token(user)
})
mail_subject = 'Bplus'
to_email = user.email
AuthEmail = EmailMessage(mail_subject, message, to=[to_email])
AuthEmail.send()
return validated_data
views.py
class UserCreateAPI(generics.GenericAPIView):
serializer_class = CreateUserSerializer
def post(self, request, *args, **kwargs):
if len(request.data["username"]) < 4 or len(request.data["password"]) < 8:
body = {"message":"short field"}
return Response(body, status = 400)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
user_for_auth = User.objects.get(username=user['username'])
login(request, user)
return Response(
{
"user":UserSerializer(
user, context=self.get_serializer_context()
).data,
"token":AuthToken.objects.create(user_for_auth),
}
)
How can I fix this error?
Your serializer create method returns the validated data instead of the created object. Since that is a dict, that is what you end up passing to the login function.
You should have return user instead of return validated_data.