Reputation: 1
I have a question about how I can update an instance in django rest framework.
So basically I want to update my user profile through an request but I cannot get current user Id. Is there a better way to get current user and update its information? This is not working because request.user is always anonymous.
@api_view(['POST'])
def update_profile(request):
serializer = AccountSerializer(request.user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Thank you so much!
Upvotes: 0
Views: 249
Reputation: 3755
If request.user
is always anonymous here, you could:
Check to see if request.user.is_authenticated
before anything else and redirect unauthenticated users to a login page (or use a @login_required
decorator), or
Get a user
object based on data from a URL parameter/kwarg instead of basing it on the user making the request. For instance, perhaps yourapp/users/1
grabs the 1
from the URL and uses for a primary key lookup.
Upvotes: 1