When I try to pass the value of course_id using perform_create method, It shows this error...
ValueError at /course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/
Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance.
Request Method: POST
Request URL: http://127.0.0.1:8000/course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/
Django Version: 2.2.5
Exception Type: ValueError
Exception Value:
Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance.
This is my views.py
class ContentAdd(generics.ListAPIView, mixins.CreateModelMixin):
queryset = Content.objects.all()
serializer_class = ContentSerializer
def post(self, request, *args, **kwargs):
saveData = self.create(request, *args, **kwargs)
response_data = {}
response_data["data"] = saveData.data
response_data["errors"] = {}
return Response(response_data, status=status.HTTP_201_CREATED)
def perform_create(self, serializer):
id = self.kwargs.get("course_id")
serializer.save(course_id=id)
This is my serializers.py
class ContentSerializer(serializers.ModelSerializer):
class Meta:
model = Content
fields = [
'title',
'description',
'serial',
'file',
'file_type',
]
This is my model.py
class Content(models.Model):
content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
course_id = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="content_course_id", to_field='course_id')
file = models.FileField(upload_to=gen_pic_path,blank=False, null=False)
file_type = models.BooleanField(blank=False, null=False) # content/attachment
serial = models.IntegerField()
title = models.CharField(max_length=200)
description = models.TextField()
This is url path
path('course/<course_id>/add/', ContentAdd.as_view()),
You need to get your Course
for saving Content
def perform_create(self, serializer):
id = self.kwargs.get("course_id")
course = Course.objects.get(id=id)
serializer.save(course_id=course)