Reputation: 567
I'm doing some basic CRUD application with python django. Basicly, from the Front End, I want to send some raw text data, the Backend will catch It, and re-send the cleaned ones. For now, the clean method worked but for some reason, It still sending the same raw text to the Front End.
This is my code:
in models.py:
class Post(models.Model):
content = models.TextField(max_length=3000, blank=False, default='')
in serializers.py:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'content')
in views.py:
@api_view(['PUT'])
def create_post(request):
if request.method == 'PUT':
post_data = JSONParser().parse(request)
post_serializer = PostSerializer(data = post_data)
if post_serializer.is_valid():
data_to_clean= str(post_serializer.data['content']) # this is raw text (i.e: "aBcD")
cleaned = clean(data_to_clean) # this is text after cleaning (i.e: "abcd")
post_serializer.data['content'] = cleaned # update the new text
return JsonResponse(post_serializer.data, status = status.HTTP_200_OK)
return JsonResponse(post_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Can you point out what is wrong with this code. Many thanks.
Upvotes: 0
Views: 34
Reputation: 9
post_serializer is immutable you cannot change that You have to create the exact copy of that and you can do your operation
from django.http import QueryDict
@api_view(['PUT'])
def create_post(request):
if request.method == 'PUT':
post_data = JSONParser().parse(request)
post_serializer = PostSerializer(data = post_data)
if post_serializer.is_valid():
data_to_clean= str(post_serializer.data['content']) # this is raw text (i.e: "aBcD")
cleaned = clean(data_to_clean) # this is text after cleaning (i.e: "abcd")
query_dict = QueryDict('', mutable=True)
query_dict.update(post_serializer.data)
query_dict.data['content'] = cleaned # update the new text
return JsonResponse(query_dict.data, status = status.HTTP_200_OK)
return JsonResponse(query_dict.errors, status=status.HTTP_400_BAD_REQUEST)
Upvotes: 1