M
M
Maxim2018-09-04 19:23:01
Django
Maxim, 2018-09-04 19:23:01

How to add field to serialization?

I use DRF
The model does not have a field that is needed for the api to work, you need to add a token to the request.
models.py

from django.db import models
from accounts.models import User


class Post(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    like = models.BigIntegerField(default=0)
    text = models.TextField(max_length=1000, blank=True, default='')

serializers.py
from django.contrib.auth import get_user_model
from post.models import Post, User
from rest_framework.serializers import (
    CharField,
    ModelSerializer,
    SerializerMethodField,
    ValidationError
)


class PostCreationSerializer(ModelSerializer):
    token = SerializerMethodField()
    text = CharField(required=False, allow_blank=True)

    def get_token(self, obj):
        pass

    class Meta:
        model = Post
        fields = (
            'text',
            'token'
        )

    def validate(self, data):
        text = data['text']
        user = User.objects.get(id=1)
        post = Post.objects.create(owner=user, text=text)
        return data

views.py
class PostCreationAPIView(APIView):
    permission_classes = [AllowAny]
    serializer_class = PostCreationSerializer
    # queryset = Post.object.all()

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = PostCreationSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

SerializerMethodField() is read only, I need to add a token field to add to the request and impose restrictions on the creation of the model if the token is not valid. How can this be implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Tikhonov, 2018-09-05
@tumbler

In general, when they talk about a token in an API, it usually refers to authentication . In this case, the field does not need to be added to the serializer.
If you want to transfer the token right along with the rest of the fields, then you will have to make a custom field and attach validation to it .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question