User Registeration Using Django Rest Framework - django

I am trying to create a api for user Registration using the django rest framework.
I have the following models.py file
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE , primary_key = True)
mobileNumber = models.IntegerField(default=0)
avatar= models.ImageField(upload_to = 'User/' , default = '/static/User/defaultProfileImage.png')
def create_user_profile(sender, **kwargs):
if kwargs['created']:
profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_user_profile, sender=User)
This is my Serializers.py file
from rest_framework import serializers
from User.models import UserProfile
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
username = serializers.CharField()
password1 = serializers.CharField(
style={'input_type': 'password'},
write_only=True)
password2 = serializers.CharField(
style={'input_type': 'password'},
write_only=True)
email = serializers.EmailField()
class Meta:
model = User
fields = (
'id',
'username',
'password1',
'password2',
'email',
'first_name',
'last_name',
)
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = UserProfile
fields = (
'user',
'mobileNumber',
'avatar')
And following is my views.py file
from User.models import UserProfile
from .serializers import UserProfileSerializer
from rest_framework.viewsets import ModelViewSet
class UserProfileViewSet(ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
What is the best way to create a User Registeration using the api view that i have created. I tried many alternatives like overriding the create method in the UserProfile Serializer class and also the drf-writable-nested but got errors.
Please suggest me a way out. Also i want that the api is able to register users when called on by an android app.

You can do this in your Serializers.py file, this should work.
class UserSerializer(serializers.HyperlinkedModelSerializer):
mobileNumber = serializers.IntegerField()
avatar= serializers.ImageField()
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'mobileNumber', 'avatar')
def create(self, validated_data):
mobile_number = validated_data.pop('mobileNumber', None)
user = super(UserSerializer, self).create(validated_data)
user.set_password(raw_password=validated_data['password'])
user.save()
userprofile = user.userprofile
userprofile.mobileNumber = mobile_number
userprofile.save()
return user
def update(self, instance, validated_data):
mobile_number = validated_data.pop('mobileNumber', None)
userprofile = instance.userprofile
userprofile.mobileNumber = mobile_number
userprofile.save()
return super(UserSerializer, self).update(instance, validated_data)
Chuck the UserProfileSerializer for this use case, i feel here its not really needed.
Your views.py and models.py look cool to me.
Hope this helps you :-)

Related

Django Admin is not allowing me to change any user settings after implementing a AbstractUser

Following a video on Youtube I want to creat a website with different Roles for students and teachers. I also would like to save off the School ID in to the user.
Here is what I want to change but when I hit save it does nothing.
I've tried creating custom forms to use for the create and change but it doesn't seem to matter. I feel like I missed typed something in the model.py or I'm missing something. Creating users works like a charm so that's why I'm confused why it wouldn't update a user correctly. I have done a fully custom user class before but shouldn't need to for this simple of change.
In the setting is have this line
AUTH_USER_MODEL = "account_app.User"
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
class School(models.Model):
name = models.CharField('School Name', max_length=240)
address1 = models.CharField('Address 1', max_length=240)
address2 = models.CharField('Address 2', max_length=240)
city = models.CharField('City', max_length=240)
district = models.CharField('District', max_length=240)
state = models.CharField('State', max_length=2)
zip_code = models.IntegerField('Zip Code')
country =models.CharField('Country', max_length=240)
phone = models.IntegerField('School Phone Number')
time_zone = models.CharField(max_length=50)
def __str__(self):
return f'{self.name}'
class User(AbstractUser):
class Role(models.TextChoices):
ADMIN = "ADMIN", "Admin"
STUDENT = "STUDENT", "Student"
TEACHER = "TEACHER", "Teacher"
base_role = Role.ADMIN
role = models.CharField(max_length=50, choices=Role.choices)
school_id = models.ForeignKey(School,blank=True, null=True, on_delete=models.DO_NOTHING)
def save(self, *args, **kwargs):
if not self.pk:
self.role = self.base_role
return super().save(*args, **kwargs)
class StudentManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
results = super().get_queryset(*args, **kwargs)
return results.filter(role=User.Role.STUDENT)
class Student(User):
base_role = User.Role.STUDENT
student = StudentManager()
class Meta:
proxy = True
def save(self, *args, **kwargs):
if not self.pk:
self.role = User.role.STUDENT
return super().save(*args, **kwargs)
def welcome(self):
return "Only for students"
class TeacherManager(BaseUserManager):
def get_queryset(self, *args, **kwargs):
results = super().get_queryset(*args, **kwargs)
return results.filter(role=User.Role.TEACHER)
class Teacher(User):
base_role = User.Role.TEACHER
teacher = TeacherManager()
class Meta:
proxy = True
def save(self, *args, **kwargs):
if not self.pk:
self.role = User.role.TEACHER
return super().save(*args, **kwargs)
def welcome(self):
return "Only for teachers"
this is the admin.py
from django.contrib import admin
from .models import User
from .models import Student
from .models import Teacher
admin.site.register(User)
admin.site.register(Teacher)
admin.site.register(Student)
EDIT - Honestly have no clue how I fixed it but I did change my files
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from .forms import UserCreationForm
from .models import School
from .models import UserProfile
"""
*** Used to create users in the Admin
if you didn't do this it would use the default account in django.
"""
class UserCreateForm(UserCreationForm):
class Meta:
model = UserProfile
fields = ('email','first_name')
class AccountsUserAdmin(AuthUserAdmin):
# Displays accounts better on the view
list_display = ('id','username','email', 'first_name', 'last_name', 'role','is_staff')
# Used to search people at top of view
search_fields = ('username','last_name','email')
filter_horizontal = ()
list_filter = ()
add_form: UserCreateForm
## Viewing an and changing existing user
fieldsets = (
(None, {'fields': ('username','password')}),
(('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(('Important dates'), {'fields': ('last_login', 'date_joined')}),
(('Additional info'), {'fields': ('role', 'school_id')}),
)
## Adding a new User
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username','first_name','last_name','email','role','school_id','password1','password2'),}),)
admin.site.register(UserProfile, AccountsUserAdmin)
admin.site.register(School)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from .models import UserProfile, School
class RegisterUserForm(UserCreationForm):
ROLE_CHOICES =(
("ADMIN", "Admin"),
("STUDENT", "Student"),
("TEACHER", "Teacher"),)
role = forms.ChoiceField(choices=ROLE_CHOICES, required=True)
school_id = forms.ModelChoiceField(queryset=School.objects.all(), required=False)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name','email', 'role' , 'school_id' , 'password1', 'password2')
class UserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
fields = '__all__'
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.dispatch import receiver
from django.db.models.signals import post_save
class School(models.Model):
name = models.CharField('School Name', max_length=240)
address1 = models.CharField('Address 1', max_length=240)
address2 = models.CharField('Address 2', max_length=240)
city = models.CharField('City', max_length=240)
district = models.CharField('District', max_length=240)
state = models.CharField('State', max_length=2)
zip_code = models.IntegerField('Zip Code')
country =models.CharField('Country', max_length=240)
phone = models.IntegerField('School Phone Number')
time_zone = models.CharField(max_length=50)
def __str__(self):
return f'{self.name}'
class UserProfile(AbstractUser):
class Role(models.TextChoices):
ADMIN = "ADMIN", "Admin"
STUDENT = "STUDENT", "Student"
TEACHER = "TEACHER", "Teacher"
role = models.CharField(max_length=50, choices=Role.choices, blank=True, null=True)
school_id = models.ForeignKey(School,blank=True, null=True, on_delete=models.DO_NOTHING)
class UserProfileManagerTeachers(models.Manager):
def get_queryset(self):
return super(UserProfile, self).get_queryset().filter(role="TEACHER")
class UserProfileManagerStudents(models.Manager):
def get_queryset(self):
return super(UserProfile, self).get_queryset().filter(role="STUDENT")
It seems that you changed the default permissions for the Abstracted User Class, So you can try this way to add custom permission for each Model, For ex.:
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
#admin.register(User)
class CustomUserAdmin(UserAdmin):
def has_change_permission(self, request, obj=None):
return True
def has_delete_permission(self, request, obj=None):
return False
Here is the full documentation: Admin Panel Permissions Doc.

Django registration profile

I am new in django. I would like to create registration profile. I found some code but it doesn´t work for me. When I want to makemigrations I always get this error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User'
I read that I could fix it with User = get_user_model() but it looks it is doesn´t work for me.
My models.py
import random
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()
def code_generator(length=5):
numbers = '0123456789'
return ''.join(random.choice(numbers) for _ in range(length))
class RegistrationProfile(models.Model):
code = models.CharField(default=code_generator, max_length=5)
user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='registration_profile', primary_key=True)
#receiver(post_save, sender=User)
def create_registration_profile(sender, instance, **kwargs):
profile, created = RegistrationProfile.objects.get_or_create(user=instance)
if created:
profile.save()
serializer.py
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from django.contrib.auth.password_validation import validate_password
from .models import User
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True}
}
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
and views.py
from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework.permissions import AllowAny
from .serializers import RegisterSerializer
class RegisterView(generics.CreateAPIView):
queryset = User.objects.all()
permission_classes = (AllowAny,)
serializer_class = RegisterSerializer
In the end I would like to send code to email for validation. Any ideas how I could do it by most effective way?
you can do this
from django.contrib.auth.models import User
class RegistrationProfile(models.Model):
code = models.CharField(default=code_generator, max_length=5)
user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='registration_profile')
#receiver(post_save, sender=User)
def create_registration_profile(sender, instance, **kwargs):
profile, created = RegistrationProfile.objects.get_or_create(user=instance)
if created:
profile.save()

Nested AbstractUser model failing during update operation with "null value in column "user_id" violates not-null constraint"

I am creating nested abstract user "Teacher from User", My use case is "Create User" -> "Then make user to teacher"
I am able to create user and make the user to Teacher, but I am unable to update the field, In below case want to update "teacher_cost"
Model.py
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
uid = models.AutoField(verbose_name='ID',
serialize=False,
auto_created=True,
primary_key=True)
TEACHER = "Teacher"
STUDENT = "Student"
user_type = models.CharField(max_length=30, default=STUDENT)
contact_number = models.CharField(max_length=20, null=True, blank=True)
address = models.TextField(null=True, blank=True)
photo = models.ImageField(null=True, blank=True)
image = models.ImageField(upload_to='users/',
default='default/avatar.png')
approved = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if self.user_type == User.TEACHER and self._state.adding:
self.approved = False
super().save(*args, **kwargs)
#property
def dishes(self):
ret = self.teacher.dish_set.all()
if ret:
return ret
else:
return ''
class Teacher(models.Model):
uid = models.AutoField(verbose_name='ID',
serialize=False,
auto_created=True,
primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True)
teacher_cost = models.DecimalField(
max_digits=5, decimal_places=2, null=True, blank=True)
languages = models.CharField(
max_length=50, null=True, blank=True)
address = models.TextField(null=True, blank=True)
def __str__(self):
return self.user.username
Serializer.py
from rest_framework import serializers, exceptions
from django.contrib.auth.forms import PasswordResetForm
from django.conf import settings
from .models import *
from rest_auth import serializers as rest_auth_serializers
from django.utils.translation import ugettext_lazy as _
class UserDetailsSerializer(serializers.ModelSerializer):
"""
User model w/o password
"""
class Meta:
model = User
fields = ('pk', 'username', 'email',
'first_name', 'last_name', 'contact_number', 'user_type', 'photo', 'address')
read_only_fields = ('email', )
class UserTeacher(serializers.ModelSerializer):
class Meta:
model = User
fields = ('teacher',)
class TeacherDetails(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = '__all__'
class TeacherFullDetails(serializers.ModelSerializer):
user_id = serializers.CharField(source='user.uid')
username = serializers.CharField(source='user.username')
first_name = serializers.CharField(source='user.first_name')
last_name = serializers.CharField(source='user.last_name')
photo = serializers.ImageField(
source='user.photo', max_length=None, use_url=True)
class Meta:
model = Teacher
fields = ('user_id', 'username', 'first_name', 'last_name', 'photo', 'teacher_cost')
class TeacherBriefDetails(serializers.ModelSerializer):
uid = serializers.CharField(source='user.uid')
first_name = serializers.CharField(source='user.first_name')
last_name = serializers.CharField(source='user.last_name')
class Meta:
model = Teacher
fields = ('uid', 'first_name', 'last_name',)
class TeacherProfileDetails(serializers.ModelSerializer):
contact_number = serializers.CharField(source='user.contact_number', required=False)
first_name = serializers.CharField(source='user.first_name', required=False)
last_name = serializers.CharField(source='user.last_name', required=False)
email = serializers.CharField(source='user.email', required=False)
photo = serializers.ImageField(
source='user.photo', max_length=None, use_url=True, required=False)
user = UserDetailsSerializer(read_only=True)
teacher_cost = serializers.CharField()
class Meta:
model = Teacher
fields = ('user', 'first_name', 'last_name', 'contact_number', 'email', 'photo',
'bio', 'teacher_cost')
class TeacherProfileSerializer(serializers.ModelSerializer):
user = UserDetailsSerializer()
class Meta:
model = Teacher
fields = ("bio", "teacher_cost", "user")
view.py
from rest_framework import generics, viewsets, status, permissions
from .models import *
from .serializers import *
from rest_framework.response import Response
from django.db.models import Q
from .permissions import IsAuthenticatedAndOwner, IsTeacher
from django.shortcuts import get_object_or_404
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.views import APIView
import json
import logging
class TeacherProfile(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
lookup_field = "username"
def get_object(self):
if self.action == "partial_update":
return get_object_or_404(User, username=self.kwargs['username'])
return get_object_or_404(Teacher, user__username=self.kwargs['username'])
def get_serializer_class(self):
if self.action == "partial_update":
return UserDetailsSerializer
else:
return TeacherProfileDetails
class TeacherListCreateAPIView(APIView):
logger = logging.getLogger(__name__)
def get(self, request, *args, **kwargs):
teacherList = Teacher.objects.filter(user__username=kwargs["username"])
self.logger.info("Printing teacher list")
self.logger.info(teacherList)
serializers = TeacherProfileDetails(teacherList, many=True)
return Response(serializers.data)
def post(self, request, *args, **kwargs):
self.logger.info("-----------------put ------------")
serializers = TeacherProfileDetails(data=request.data)
# photo = request.FILES['file']
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, *args, **kwargs):
serializers = TeacherProfileDetails(data=request.data, many=True)
self.logger.info(serializers)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
# /user/<str:username>/profile
class UserProfile(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
lookup_field = "username"
def get_object(self):
return get_object_or_404(User, username=self.kwargs['username'])
def get_serializer_class(self):
return UserDetailsSerializer
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('teacher/<str:username>/profile',
TeacherProfile.as_view({'get': 'retrieve', 'delete': 'destroy', 'patch': 'partial_update'})),
path('teacherlist/<str:username>/',
TeacherListCreateAPIView.as_view(), name="teacher-list"),
]
Getting below error while calling post command to update the user profile
post
http://localhost:8002/api/v1/teacherlist/rayees/
Form json data
{
"teacher_cost": "25.00"
}
Getting below error
IntegrityError at /api/v1/teacherlist/rayees/
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 25.00, null, null, null).
Request Method: POST
Request URL: http://localhost:8002/api/v1/teacherlist/rayees/
Django Version: 2.2.4
since in model Teacher user is required fields, and you are sending the post request, it will create the new teacher with that user.If you want create new teacher then you should use the post, for that you need the user
if you want update the details of the user you can use patch method, checkout the put method code
class TeacherListCreateAPIView(APIView):
logger = logging.getLogger(__name__)
def get(self, request, *args, **kwargs):
teacherList = Teacher.objects.filter(user__username=kwargs["username"])
self.logger.info("Printing teacher list")
self.logger.info(teacherList)
serializers = TeacherProfileDetails(teacherList, many=True)
return Response(serializers.data)
def post(self, request, *args, **kwargs):
""" creating new user """
serializers = TeacherProfileDetails(data=request.data)
# photo = request.FILES['file']
if serializers.is_valid():
serializer.validated_data['user'] = User.objects.filter(username=kwarsg['username'])
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, *args, **kwargs):
teacher = TeacherProfileDetails.objects.get(user__username=kwargs['username'])
serializers = TeacherProfileDetails(data=request.data, instance=teacher)
self.logger.info(serializers)
if serializers.is_valid():
serializers.save()
return Response(serializers.data, status=status.HTTP_201_CREATED)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
now you can make patch request on http://localhost:8002/api/v1/teacherlist/rayees/
with given data it will update the record.

Add more field in SignupForm using django-allauth

Models:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
nationality = models.CharField(max_length=20)
def __str__(self):
return self.user.first_name
#receiver(post_save, sender=User)
def create_user_profile(self, sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(self, sender, instance, **kwargs):
instance.profile.save()
Forms:
from allauth.account.forms import SignupForm
class CustomSignupForm(SignupForm):
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'nationality', 'bio')
def signup(self, request, user):
# Save your user
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
user.profile.nationality = self.cleaned_data['nationality']
user.profile.gender = self.cleaned_data['bio']
user.profile.save()
Views:
ACCOUNT_FORMS = {'signup': 'myproject.forms.CustomSignupForm',}
This process isn't work. Error is: Model class all_auth.models.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
How can I solve it? Or, How can i add more field with SignupForm using django-allauth?
Create an application, such as accounts and it has this code, but you need to create a database only after creating this code, it is more accurate to perform the first migration in the project
accounts/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
phone = models.CharField(max_length=12)
accounts/forms.py
from allauth.account.forms import SignupForm
from django import forms
from .models import *
class SimpleSignupForm(SignupForm):
phone = forms.CharField(max_length=12, label='Телефон')
def save(self, request):
user = super(SimpleSignupForm, self).save(request)
user.phone = self.cleaned_data['phone']
user.save()
return user
settings.py
...
ACCOUNT_FORMS = {'signup': 'accounts.forms.SimpleSignupForm'}
AUTH_USER_MODEL = 'accounts.CustomUser'
accounts/admin.py
from django.contrib import admin
from .models import *
admin.site.register(CustomUser)

How to create a new user with django rest framework and custom user model

I have a custom user model and I am using django-rest-framework to create API
models.py:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
unique=True,
max_length=254,
)
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=15)
mobile = models.IntegerField(unique=True)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
serializers.py:
class UserSerializer(serializers.ModelSerializer):
password1 = serializers.CharField(write_only=True)
password2 = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'mobile', 'password1', 'password2')
views.py:
#api_view(['POST'])
#permission_classes((AllowAny,))
def create_user(request):
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
User.objects.create_user(
serialized.save()
)
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
However, when I try to create a new user I am getting this error:
Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly.
This maybe because there's no password1 or password2 fields in the User model. But so, how can I create an API to create a new user using django-rest-framework?
I think one password field is enough. If you want to check the user's twice password input is same, do it in the front-end. You can override a create method from serializer like following.
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'mobile', 'password')
def create(self, validated_data):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
views.py
from rest_framework import generics
from rest_framework.permissions import AllowAny
from .models import User
from .serializers import UserSerializer
class UserCreateAPIView(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (AllowAny,)