简体   繁体   English

如何在Django rest框架中更新实例?

[英]How to update an instance in Django rest framework?

I have a question about how I can update an instance in django rest framework. 我有一个关于如何在django rest框架中更新实例的问题。

So basically I want to update my user profile through an request but I cannot get current user Id. 因此,基本上我想通过请求更新我的用户个人资料,但无法获取当前用户ID。 Is there a better way to get current user and update its information? 有没有更好的方法来获取当前用户并更新其信息? This is not working because request.user is always anonymous. 这是行不通的,因为request.user始终是匿名的。

@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! 非常感谢!

If request.user is always anonymous here, you could: 如果request.user在此处始终是匿名的,则可以:

  1. 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 首先检查一下request.user.is_authenticated然后将未经身份验证的用户重定向到登录页面(或使用@login_required装饰器),或者

  2. Get a user object based on data from a URL parameter/kwarg instead of basing it on the user making the request. 根据来自URL参数/ kwarg的数据获取user对象,而不是基于发出请求的用户。 For instance, perhaps yourapp/users/1 grabs the 1 from the URL and uses for a primary key lookup. 例如,也许yourapp/users/1从URL中获取1并用于主键查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM