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,
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."
]
}
How can i fill "author" part automatically using Token (or other way not using Token)?
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"
.