我几乎是django和rest框架的新手。我想从客户端获取请求数据并保存模型的对象。在我的view.py
文件中,我有一个从APIView
扩展的类(例如名为 CreateUser(APIView)。从客户端,我想发布一个JSON文件并获取它在这个视图中并保存在我的模型中。我该如何处理它?</ p>
我的学生课程是:
from django.contrib.auth.models import User
from django.db import models
class Student(models.Model):
user = models.ForeignKey(User)
grade = models.IntegerField()
我为学生班创建了一个序列化程序。
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
我想获得一个带有用户名密码和等级的JSON对象,并将其保存在我的模型中。
答案 0 :(得分:2)
您需要实现APIView
的post()方法。要将发布的数据传递给序列化程序实例,请使用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)
要设置用户密码,请在序列化程序的create中使用set_password()
。密码字段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
注意 Student.objects.create
不要将self
作为第一个参数。