H.fate H.fate - 2 months ago 22
Android Question

DRF(django-rest-framework) and TokenAuthentication, how to fill json field automatically based Token?

settings.py

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}


serializers.py

class UserSerializer(serializers.ModelSerializer):
related_postwriter = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('id', 'username', 'email', 'related_postwriter')

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'created_date', 'author', 'text', 'image')
def create(self, validated_data):
validated_data['author'] = self.context['request'].user
return super(PostSerializer, self).create(validated_data)


models.py

class Post(models.Model):
author = models.ForeignKey(User, related_name='related_postwriter')
text = models.TextField(blank = False)
image = models.ImageField(null = False, blank = False, upload_to='images')
created_date = models.DateTimeField(
default=timezone.now
)

def __str__(self): # __unicode__ on Python 2
return self.text


views.py

class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
queryset = Post.objects.all()


I had to make this RESTful api for json request and json response.
When i use this RESTful api for Android application, I learned that i login and get Token from RESTful api, and then that Token is used to post data to RESTful api through Header.

As postman capture,

enter image description here

I must fill "author":"number" on Body. I think this number means that user's registering order on my RESTful api. From above capture, that author is first user of my RESTful api.

If i made author field empty, it returned

{
"author": [
"This field is required."
]
}



  1. How can i fill "author" part automatically using Token (or other way not using Token)?

  2. How can i get json response
    "author":"some alphabet name readable"
    , not
    "author":"1 or 2 like number"
    as capture. I want form like
    "author":"stackoverflowman"
    .


Answer

for you first question, you should add in PostViewSet this function:

def perform_create(self, serializer):
     serializer.save(author=self.request.user)

for your second question, you should call the UserSerializer from PostSerializer:

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)

    class Meta:
        model = Post
        fields = ('id', 'created_date', 'author', 'text', 'image')

EDIT

if you only want one field, you can declare a field with source:

class PostSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')

    class Meta:
        model = Post
        fields = ('id', 'created_date', 'author', 'text', 'image')
Comments