简体   繁体   中英

Django POST Request: I always end up with an Error 400 and the provided data in the request doesn't get accepted

I have a django project with the following (relevant to this question) apps: Course, Category, User (Teacher) & SubCategory.

Using the Django REST Framework, I am trying to override the perform_create() method, so that certain fields of the Course Model are already preoccupied when creating a new instance. I'd like the "teacher" field to be the current user, the "category" field to be the instance of the category, which is matched by the request data "category", etc.

Now whenever I execute the code, I end up with a 400 Error and it says that "This field is requied" for the teacher, category, sub_category, etc.

Please find the code below:

Course Model

class Course(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    premium_only = models.BooleanField(default=False)
    duration = models.IntegerField(default=0)
    level = models.CharField(max_length=100)

    # Relationships
    category = models.ForeignKey(
        to=Category, related_name='courses', on_delete=models.CASCADE)
    sub_category = models.ForeignKey(
        to=SubCategory, related_name='courses', on_delete=models.CASCADE)
    teacher = models.ForeignKey(
        to=User, related_name='courses', on_delete=models.CASCADE)
    marked_as_favorite_by = models.ManyToManyField(
        to=User, related_name='favorite_courses', blank=True, null=True, default=None)

    def __str__(self):
        return self.name

Course Views

class CreateCourseView(CreateAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        categories = Category.objects.all()
        sub_categories = SubCategory.objects.all()
        teacher = self.request.user
        category = categories.get(name=self.request.data['category'])
        sub_category = sub_categories.get(
            name=self.request.data['sub_category'])
        serializer.save(teacher=teacher, category=category,
                    sub_category=sub_category)

Serializer

from user.nested_serializers.teacher_for_course import CourseTeacherSerializer
from rest_framework import serializers
from .models import Course
from category.nested_serializers.for_course import CourseCategorySerializer
from sub_category.nested_serializers.for_course import CourseSubCategorySerializer


class CourseSerializer(serializers.ModelSerializer):
    category = CourseCategorySerializer()
    sub_category = CourseSubCategorySerializer()
    teacher = CourseTeacherSerializer()
    marked_as_favorite_by = CourseTeacherSerializer(many=True)

    class Meta:
        model = Course
        fields = ('id', 'name', 'description', 'created_at',
                  'updated_at', 'premium_only', 'duration', 'level', 'category', 'sub_category', 'teacher', 'marked_as_favorite_by')

Is that enough information for you to be able to help me?

Thanks in advance!

I should've used read_only = True in the serializer. This worked!

class CourseSerializer(serializers.ModelSerializer):
    category = CourseCategorySerializer(read_only=True)
    sub_category = CourseSubCategorySerializer(read_only=True)
    teacher = CourseTeacherSerializer(read_only=True)
    marked_as_favorite_by = CourseTeacherSerializer(read_only=True, many=True)

class Meta:      
    model = Course
    fields = ['id', 'name', 'description', 'created_at',
              'updated_at', 'premium_only', 'duration', 'level', 'teacher', 'marked_as_favorite_by', 'category', 'sub_category']
    read_only_fields = ['teacher', 'marked_as_favorite_by', 'category', 'sub_category']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM