0

I am almost new to django and rest framework. I want to get data on a request from client side and save a model's object. In my view.py file I have a class that extends from APIView(for example named CreateUser(APIView). From the client side, I want to post a JSON file and get it in this view and save it in my models. How can I handle it?

My Student class is:

from django.contrib.auth.models import User from django.db import models class Student(models.Model): user = models.ForeignKey(User) grade = models.IntegerField() 

I have created a serializer for my Student class.

from rest_framework import serializers from users.models import Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('username', 'password', 'grade') def create(self, validated_data): user = validated_data.get('user') grade = validated_data.get('grade') student = Student.objects.create(self, user=user, grade=grade) return student 

I want to get a JSON object with username password and grade and save it in my models.

1 Answer 1

3

You need to implement APIView's post() method. To pass posted data to serializer instance use request.data:

class CreateUser(APIView): def post(self, request, format=None): serializer = StudentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 

To set user password use set_password() inside serializer's create. Also it's a good idea to make password field write_only:

class StudentSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = Student fields = ('username', 'password', 'grade') def create(self, validated_data): user = validated_data.get('user') grade = validated_data.get('grade') student = Student.objects.create(user=user, grade=grade) student.set_password(validated_data.get('password') return student 

Note Student.objects.create dont take self as first argument.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much for your response. I have implemented drf docs in my project but when I go to docs. I cannot see my createuser endpoint. url(r'^signup/', CreateUser.as_view, name='create_user'),, I wrote this in my urls.py. do you know why I cannot see that?
@salehsereshki Do you set permission_classes for the view? Probbaly user with whom you are logged in dont have permissions to this view, and so you cannot see it in docs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.