Home > Mobile >  Create User in django using Rest Framework
Create User in django using Rest Framework

Time:08-21

i've seen people using different ways to create user in django Rest framework. i tried & none of them is working for me. sometimes it says Key error: Groups or something else. so i tried this without having a is_valid & it works like a charm. is this a safe way to use to create user or if not why & how should i create User in views?

#my views.py

@api_view(['GET','POST'])
def getUserData(request):
    if request.method == 'POST':
        user = User.objects.create_user(
        username=request.data['username'],
        password=request.data['password'])
        serializer = userSerializer(user)
    return Response(serializer.data)

CodePudding user response:

well i would love to user the validated data from the serializer first as follows:

@api_view(['GET','POST'])
def getUserData(request):
    if request.method == 'POST':
        serializer = userSerializer(user)
        username = serializer.validated_data.get('username')
        password = serializer.validated_data.get('password')
        user = User.objects.create_user(username=username, password=password)
    return Response(serializer.data)

CodePudding user response:

change the view as below this works around too,

    @api_view(["GET", "POST"])
def getUserData(request):
        if request.method == "POST":
            serializer = UserSerializer(data=request.data)
            if serializer.is_valid():
               serializer.save()
               return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_400_BAD_REQUEST)

here is the UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    username=serializers.CharField()
    password=serializers.CharField()
    class Meta:
        model = User
        fields=['username','password']
        

and models.py(I'm using custom user model but no changes from original user model which is provided by Django itself):

from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    pass
  • Related