I am new to DRF. While creating the twitter app I faced a problem with serializers. Since the user is required - I need somehow to pass the actual user to the TweetSerializer class. I have tried different methods that did not work.
This is giving me an error
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
also i have tried to se the user by passing it tot he serializer constructor
serializer = TweetSerializer(owner=request.user)
also did not work
class TweetSerializer(serializers.ModelSerializer):
try:
owner = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
except Exception as exception:
print(exception)
class Meta:
model = Tweet
fields = '__all__'
read_only_fields = ['owner']
def validate(self, attrs):
if len(attrs['content']) > MAX_TWEET_LENGTH:
raise serializers.ValidationError("This tweet is too long")
return attrs
class Tweet(models.Model):
id = models.AutoField(primary_key=True)
owner = models.ForeignKey('auth.User', related_name='tweets', on_delete=models.CASCADE)
content = models.TextField(blank=True, null=True)
image = models.FileField(upload_to='images/', blank=True, null=True)
class Meta:
ordering = ['-id']
@api_view(['POST'])
def tweet_create_view(request, *args, **kwargs):
serializer = TweetSerializer(data=request.POST)
user = request.user
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors)
return JsonResponse({}, status=400)
try:
pass
except Exception as e:
print(str(e))
return JsonResponse({}, status=400, safe=False)
return JsonResponse({}, status=201)
The solution was to pass a context as I read from drf documentation for CurrentUserDefault()
@api_view(['POST'])
def tweet_create_view(request, *args, **kwargs):
context = {
"request" : request
}
serializer = TweetSerializer(data=request.POST, context=context)
if serializer.is_valid():
serializer.save()
return JsonResponse({}, status=201)
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.