2👍
This is what the documentation of CurrentUserDefault
says:
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.
You can either do that or you can provide the email id passed in the context data
in your views
. Override the function get_serializer_context
def get_serializer_context(self):
context = super(YourClass, self).get_serializer_context()
context['email'] = request.user.email
return context
in your views
. Your view
should be extended from GenericAPIView
at some level of inheritance. Now in your serializer
, override your __init__
and get your email data.
def __init__(self, instance = None, data = serializers.empty, *args, **kwargs):
self.email = kwargs['context']['email']
Now you can use that in your serializer.
2👍
Please check solution 2 from this answer
The code can be:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email',)
extra_kwargs = {
'email': {'read_only': True},
}
def create(self, validated_data):
"""Override create to provide a email via request.user by default."""
if 'email' not in validated_data:
validated_data['email'] = self.context['request'].user.email
return super(UserSerializer, self).create(validated_data)
hope it help 🙂
- [Django]-Copy in Postgresql: Absolute Path Interpreted as Relative Path
- [Django]-Django allauth social login(google OAuth 2) – limit list of domains
- [Django]-Getting the right dependency in Heroku
- [Django]-Sort list of dictionaries based on nested keys
- [Django]-Comet framework for Django
Source:stackexchange.com