I have this problem for a month.
I'm using abstractbasemodel and basemanagerto to create a login and signup API using rest framework.
However, when I create a user password, it is saved as raw data since I use set_password() method and custom model manager confuses me...
This is my code :
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = validated_data['password']
)
class UserProfileViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserProfileSerializer
queryset = models.UserProfile.people.all()
authentication_classes = (TokenAuthentication, )
permission_classes = (UpdateOwnProfile, )
filter_backends = (SearchFilter, )
search_fields = ('name', 'email')
class UserLoginApiView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
print("user model manager")
if not email:
raise ValueError('User Must Have an Email Address')
email = self.normalize_email(email)
user = self.model(email=email, name=name )
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(max_length=255,unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
people = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def __str__(self):
return self.email
class Profile(models.Model):
user = models.OneToOneField(UserProfile,on_delete=models.CASCADE,relat ed_name="Profile")
location = models.CharField(max_length=100,blank=True,null=True)
bio = models.CharField(max_length=100,blank=True,null=True)
creationDate = models.DateTimeField(auto_now_add=True)
follower = models.ManyToManyField(UserProfile,related_name="Following",blank=True)
class Meta:
verbose_name='Profile'
verbose_name_plural='Profiles'
I also defined auth user model in settings :
AUTH_USER_MODEL='profiles.UserProfile'
to make sure Django uses my custom user model.
I don't know whats wrong as there is no error and only superusers that are created in terminal using manage.py are saved with hashed password.
Users which are created with my viewsets are saved with raw password.
First, I named the model manager "objects" and now, its people but the create user method wont run at all.
You can use django's built in hasher to create hashed password. It can be applied in .create method. First import from django.contrib.auth.hashers import make_password and then modify .create() method,
def create(self, validated_data):
user = UserProfile.people.create_user(
email = validated_data['email'],
name = validated_data['name'],
password = make_password(validated_data['password']) # here
)
return user
Or
if you don't override the .create() method then add the following validate_password method in serializer,
The validate_password is ran, everytime a new object has to be created
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id' ,'email' ,'name' ,'password')
extra_kwargs = {
'password':{
'write_only':'True',
'style': {'input_type': 'password'}
}
}
def validate_password(self, value: str) -> str:
return make_password(value)
Related
I am using DRF and I have these pieces of code as models, register view and serializer
But anytime I signup a user the password does not hashed and I can't see to figure out why.
models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
if not email:
raise ValueError("Users must have an email")
email = self.normalize_email(email).lower()
user = self.model(email=email, **kwargs)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
if not password:
raise ValueError("Password is required")
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
role = models.CharField(max_length=255)
department = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_verified = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name", "role", "department"]
def __str__(self):
return self.email
serializers.py
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.CharField(max_length=255)
password = serializers.CharField(min_length=8, write_only=True)
first_name = serializers.CharField(max_length=255)
last_name = serializers.CharField(max_length=255)
role = serializers.CharField(max_length=255)
department = serializers.CharField(max_length=255)
class Meta:
model = User
fields = ["email", "password", "first_name", "last_name", "role", "department"]
def create(self, validated_data):
return User.objects.create(**validated_data)
def validate_email(self, value):
if User.objects.filter(email=value).exists():
raise serializers.ValidationError("This email already exists!")
return value
views.py
class RegisterView(APIView):
serializer_class = RegisterSerializer
def post(self, request, *args):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data.get("email"))
return Response(user_data, status=status.HTTP_201_CREATED)
for some reason, which I don't know anytime a user is created the password is save in clear text. It does not hash the passwords. The superuser's password is however hashed because I created it with the command line but the api doesn't hash the password. I some help to fix this.
Instead of passing plain password you should use make_password method provided by django.
from django.contrib.auth.hashers import make_password
make_password(password, salt=None, hasher='default')
Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text (string or bytes). Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of PASSWORD_HASHERS setting). See Included hashers for the algorithm name of each hasher. If the password argument is None, an unusable password is returned (one that will never be accepted by check_password()).
You can try something like this
hashed_pass = make_password(your_password_here, salt=None, hasher='default')
user = self.create_user(email, hashed_pass)
Source: https://docs.djangoproject.com/en/4.1/topics/auth/passwords/
Try this:
def create(self, validated_data):
password = validated_data.pop('password')
user = User.objects.create(**validated_data)
user.set_password(password)
user.save()
return user
I found why it wasn't working. In the create method in the RegisterSerializer I did a return User.objects.create(**validated_data)
which saves on the request data in the database, including the password without hashing it first. The correct way is to be calling the create_user method instead, like so return User.objects.create_user(**validated_data) since that method has the set_password mechanism to hash the password.
I am Trying To create a API for my custom user model to register a user and get details about current user that is logged in .
I tried to Follow a tutorial but I faced 2 problems, 1.The confirmation password is not being hashed when creating a user, 2. The Get method didn't work ( I was Trying to Get User details Using the id, it didn't return any thing except bad request responce ).
I hope any one can help me.
This is my models.py:
from django.db import models
from django import forms
# Create your models here.
from django.db import models
from django.contrib.auth.models import (
AbstractUser,
BaseUserManager,
AbstractBaseUser
)
from django.forms import Widget
from django.urls import reverse
class CustomUserManager(BaseUserManager):
def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False):
if not email:
raise ValueError('User Must Have Email')
if not password:
raise ValueError('User Must Have Password')
user_obj = self.model(
email = self.normalize_email(email)
)
user_obj.set_password(password)#change user password
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self,email,password=None):
user = self.create_user(
email,
password = password,
is_staff = True
)
return user
def create_superuser(self,email,password=None):
user = self.create_user(
email,
password = password,
is_staff = True,
is_admin = True,
)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length= 200)
first_name = models.CharField(max_length = 300)
last_name = models.CharField(max_length = 300)
email = models.EmailField(max_length=255,unique=True)
password = models.CharField(max_length=100,)
password_2 = models.CharField(max_length=100,)
sub_to_newsletter = models.BooleanField(default=True)
own_pc = models.BooleanField(default=False)
active = models.BooleanField(default=True) #can login
staff = models.BooleanField(default=False) #staff user not superuser
admin = models.BooleanField(default=False) #admin / superuser
USERNAME_FIELD = 'email' #username
#email and password is requierd by default
REQUIRED_FIELDS = [] #python manage.py createsuperuser
objects = CustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(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):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
def get_absolute_url(request):
return reverse('')
This is my forms.py:
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ReadOnlyPasswordHashField
User = get_user_model()
class UserAdminCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password = forms.CharField(widget=forms.PasswordInput())
password_2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput())
class Meta:
model = User
fields = ['email']
def clean(self):
'''
Verify both passwords match.
'''
cleaned_data = super().clean()
password = cleaned_data.get("password")
password_2 = cleaned_data.get("password_2")
if password is not None and password != password_2:
self.add_error("password_2", "Your passwords must match")
return cleaned_data
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password"])
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']
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"]
This is admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import *
from .forms import *
User = get_user_model()
# Register your models here.
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserAdminChangeForm
add_form = UserAdminCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ['email', 'admin']
list_filter = ['admin']
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('username','first_name','last_name','sub_to_newsletter','own_pc')}),
('Permissions', {'fields': ('admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password', 'password_2')}
),
)
search_fields = ['email']
ordering = ['email']
filter_horizontal = ()
admin.site.register(User,UserAdmin)
I suggest that you remove password_2 from your user model. There is no reason to store the password twice. The purpose of a "confirm password" is to force the user to enter the same password twice in order to eliminate typos.
You can keep password_2 as a form field. Then add field validation to check that password and password_2 are the same.
i have a custom user model that looks like this
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
# user manager code
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves a User with the given email, first name,
last name and password.
"""
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
# Create your models here.
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return self.email
my serializer.py
class RegisteSerializer(serializers.Serializer):
password = serializers.CharField(style={"input_type": "password"},
write_only=True)
password2 = serializers.CharField(style={"input_type": "password"},
write_only=True)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
first_name = serializers.CharField(min_length=2, max_length=50)
last_name = serializers.CharField(min_length=2, max_length=50)
USERNAME_FIELD = 'email'
class Meta:
model = User
fields = [
'id',
'first_name',
'last_name',
"email",
"password",
"password2",
]
extra_kwargs = {'password': {'write_only': True}}
def validate_email(self, email):
email = get_adapter().clean_email(email)
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(
("A user is already registered with this e-mail address."))
return email
def validate_password(self, password):
return get_adapter().clean_password(password)
def validate(self, data):
if data['password'] != data['password2']:
raise serializers.ValidationError(
("The two password fields didn't match."))
return data
def get_cleaned_data(self):
return {
'first_name': self.validated_data.get('first_name', ''),
'last_name': self.validated_data.get('last_name', ''),
'password': self.validated_data.get('password', ''),
'password2': self.validated_data.get('password', ''),
'email': self.validated_data.get('email', ''),
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
adapter.save_user(request, user, self)
setup_user_email(request, user, [])
user.save()
return user
when i register using endpoint http://127.0.0.1:8000/api/dj-rest-auth/registration/
i am greeted with all fields the way i want it
but when i try to login http://127.0.0.1:8000/api/dj-rest-auth/login/
i still see username
even after configuring my django allauth
# django-allauth configuarations
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
i am new to django rest framework i dont want to rewrite everything i dont even know how
I am a newbie at Django and I have come across this problem with my code.
I have a Custom User Model and an Account model which are related by many-to-many field.
During SignUp a user is asked to either create an Account or not ( join other account through a link ).
If the User creates an Account then he is the owner of the account and other Users can join the account.(Did not finish the code for ownership)
One User can be a part of several accounts at the same time.
Creation of Account(or not) and the User takes place in the Signup view.
I read up about the nested serializer in the documentation and i think this should create the two models instances.
How to create relationships in one view using nested serializers?
Other Approaches to solve the issue?
Models
class Account(models.Model):
AccountName = models.TextField(max_length=100, blank=False, null=False)
class User(AbstractBaseUser):
AccountName = models.ManyToManyField(Account)
CreateAccount = models.BooleanField(blank=False, null=False)
EmailId = models.EmailField(max_length=128, blank=False, null=False, unique=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 = 'EmailId'
REQUIRED_FIELDS = ['AccountName', 'CreateAccount',]
# Implemented the other req. functions
objects = MyAccountManager()
Serializers
class AccountCreationSerializer(ModelSerializer):
class Meta:
model = Account
fields = ['AccountName']
class SignUpSerializer(ModelSerializer):
AccountName = AccountCreationSerializer()
class Meta:
model = User
fields = ['EmailId', 'AccountName', 'CreateAccount', 'password']
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def create(self, validated_data):
AccountName = validated_data.pop('AccountName')
if validated_data['CreateAccount']: #Create only when this is True
Account.objects.create(AccountName=AccountName, **AccountName)
userAcc = User.objects.create_user(**validated_data)
return userAcc
View
class SignUpView(APIView):
def post(request):
# to edit
signup_serializer = SignUpSerializer(data=request.data)
# rest of the view
The request
// Ignoring the quotes
EmailID: xyz#gmail.com
AccountName: TestAcc
CreateAccount: False
Password: ****
Error:
Direct assignment to the forward side of a many-to-many set is prohibited. Use AccountName.set() instead.
Create_user in Custom model
def create_user(self, EmailId, AccountName, CreateAccount, password):
if not EmailId:
raise ValueError("Users must have an email")
user = self.model(
EmailId=self.normalize_email(EmailId),
AccountName=AccountName,
CreateAccount=CreateAccount,
)
user.set_password(password)
user.save(using=self._db)
return user
I am pretty sure I am making some mistake regarding the manytomany field but haven't been able to figure out the solution. Any help would be of benefit to me. TIA!
You can not save value directly to many-to-many field. Database does not allow you to do so. It only allows you to add them for associating the relationship between the two tables ( i.e User, Account ). Replace your code segment for Serializer file with the following one.
class AccountCreationSerializer(ModelSerializer):
class Meta:
model = Account
fields = ['AccountName']
class SignUpSerializer(ModelSerializer):
AccountName = serializers.SerializerMethodField()
class Meta:
model = User
fields = ['EmailId', 'AccountName', 'CreateAccount', 'password']
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def validate(self, attrs):
attrs = super(SignUpSerializer, self).validate(attrs=attrs)
attrs.update({"AccountName": self.initial_data.get("AccountName")})
return attrs
def create(self, validated_data):
AccountName = validated_data.pop('AccountName')
acc = Account.objects.create(AccountName=AccountName) if "CreateAccount" in validated_data and validated_data['CreateAccount'] else None
userAcc = User.objects.create_user(**validated_data)
if acc:
userAcc.AccountName.add(acc)
return userAcc
Finally, replace your SignUpView class in the following way:
class SignUpView(APIView):
serializer_class = SignUpSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
is_valid_serializer = serializer.is_valid(raise_exception=True)
if is_valid_serializer:
with transaction.atomic():
serializer.save()
# Rest of your code segments to finalize the response
UPDATE
There is a problem with your create_user method. You are here passing the many-to-many field reference (AccountName), which you shouldn't. As I mentioned earlier, you can not save directly many-to-many field. You just need to associate the relation between them. Omit that and it will work!!!
Follow this new definition for this method (create_user).
def create_user(self, EmailId, CreateAccount, password):
if not EmailId:
raise ValueError("Users must have an email")
user = self.model(EmailId=self.normalize_email(EmailId), CreateAccount=CreateAccount)
user.set_password(password)
user.save(using=self._db)
return user
models.py
class UserManager(BaseUserManager):
def create_user(self, phone, password=None):
if not phone:
raise ValueError('Please provide a valid Phone')
user = self.model(
phone = phone,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, phone, password):
user = self.create_user(
phone,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, phone, password):
user = self.create_user(
phone,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
phone_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}',
message="Phone number should be in the format '+9999999999', Up to 14 digits allowed.")
class User(AbstractBaseUser):
phone = models.CharField(validators=[phone_regex],max_length=15,unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.phone
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
admin.py
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('phone',)
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):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('phone', 'password')
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 UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('phone', 'admin')
list_filter = ('admin',)
fieldsets = (
(None, {'fields': ('phone', 'password')}),
('Personal info', {'fields': ()}),
('Permissions', {'fields': ('admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('phone', 'password1', 'password2')}
),
)
search_fields = ('phone',)
ordering = ('phone',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
admin.site.register(PhoneOTP)
admin.site.unregister(Group)
serializers.py
User = get_user_model()
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('phone','password')
extra_kwargs = {"password":{'write_only': True}}
def create(self,validated_data):
user = User.objects.create(validated_data['phone'],None,validated_data['password'])
return user
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id','phone']
class LoginSerializer(serializers.Serializer):
phone = serializers.CharField()
password = serializers.CharField(style= { 'input_type': 'password'},trim_whitespace=False)
def validate(self, data):
user = authenticate(**data)
if user.phone and user.password:
return user
raise serializers.ValidationError("Unable to log in with provided credentials.")
When I try to create user using APIView the user is created and I can see the user in the Django admin as well but the password field is unhashed and it says Invalid password format or unknown hashing algorithm. I have used a custom user model here to use the phone number as the username field but the problem remains the same. I am on the current version of Django i.e, 2.2 and because of this, I am also not able to login into the app as well.
use set_password() method for creating password
or
use User.objects.create_user() for your code.
Edit your code like this.
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('phone','password')
extra_kwargs = {"password":{'write_only': True}}
def create(self,validated_data):
user = User.objects.create_user(validated_data['phone'],None,validated_data['password'])
return user
I used this, and worked well.
class CreateUser(APIView):
permission_classes = [AllowAny]
def post(self, request, format='json'):
print(request.data)
data = request.data
reg_serializer = RegisterUserSerializer(data=data)
if reg_serializer.is_valid():
password = reg_serializer.validated_data.get('password')
reg_serializer.validated_data['password']=make_password(password)
new_user = reg_serializer.save()
if new_user:
return Response(status=status.HTTP_201_CREATED)
return Response(reg_serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Write the create method outside the meta class and it will work.
This solved this problem for me:
USERS = {
"a_user_name" : ["User group","email#domain.com","Password1234*"],
}
for user_name in USERS:
new_user, created = User.objects.get_or_create(username=user_name,is_staff = True, email = USERS[user_name][1])
new_user.set_password(USERS[user_name][2])
new_user.save()
try this
from django.contrib.auth.hashers import make_password
...
def create(self,validated_data):
user = User.objects.create(validated_data['phone'],None,make_password(validated_data['password']))
return user
In view.py "use make_password()"
if validated:
temp_data = {
'phone': phone,
'password': make_password(password),
}