92π
I found the answer looking through the DRF source code.
class ActivitySerializer(serializers.ModelSerializer):
# Create a custom method field
current_user = serializers.SerializerMethodField('_user')
# Use this method for the custom field
def _user(self, obj):
request = self.context.get('request', None)
if request:
return request.user
class Meta:
model = Activity
# Add our custom method to the fields of the serializer
fields = ('id','current_user')
The key is the fact that methods defined inside a ModelSerializer
have access to their own context, which always includes the request (which contains a user when one is authenticated). Since my permissions are for only authenticated users, there should always be something here.
This can also be done in other built-in djangorestframework serializers.
As Braden Holt pointed out, if your user
is still empty (ie _user
is returning None
), it may be because the serializer was not initialized with the request as part of the context. To fix this, simply add the request context when initializing the serializer:
serializer = ActivitySerializer(
data=request.data,
context={
'request': request
}
)
68π
A context is passed to the serializer in REST framework, which contains the request by default. So you can just use self.context['request'].user
inside your serializer.
- [Django]-Django: Redirect to previous page after login
- [Django]-How to get a particular attribute from queryset in Django in view?
- [Django]-Django β accessing the RequestContext from within a custom filter
4π
I had a similar problem β I tried to save the model that consist user in, and when I tried to use
user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
like on official documentation β but it throws an error that user is 'null'
. Rewrite the default create
method and get a user from request helped for me:
class FavoriteApartmentsSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
class Meta:
model = FavoriteApartments
exclude = (
'date_added',
)
def create(self, validated_data):
favoriteApartment = FavoriteApartments(
apartment=validated_data['apartment'],
user=self.context['request'].user
)
favoriteApartment.save()
return favoriteApartment
- [Django]-Factory-boy create a list of SubFactory for a Factory
- [Django]-How can I test binary file uploading with django-rest-framework's test client?
- [Django]-How do I display the Django '__all__' form errors in the template?
0π
Actually, the new way to do this is by using HiddenField
β
view drf documentation:
class ReportSerializer(serializers.ModelSerializer):
author = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = Report
fields = ('id', 'type', 'name', 'post', 'comment', "author")
Make sure to add isAuthenticated
to the permissions class when you do this or else it gives errors when saving.
However, if the it is optional, just create your own class as by using the example from the docs.
So simply make the field optional by setting required
to false
,
then create your own class as such:
class CurrentUserDefault:
requires_context = True
def __call__(self, serializer_field):
if serializer_field.context['request'].is_authenticated:
return None
return serializer_field.context['request'].user
- [Django]-How to properly use the "choices" field option in Django
- [Django]-Django's Double Underscore
- [Django]-How do you catch this exception?
-2π
I modified the request.data:
serializer = SectionSerializer(data=add_profile_data(request.data, request.user))
def add_profile_data(data, user):
data['user'] = user.profile.id
return data
- [Django]-What are the differences between django-tastypie and djangorestframework?
- [Django]-How can I render a tree structure (recursive) using a django template?
- [Django]-Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT