简体   繁体   English

django rest框架用户注册

[英]django rest framework user registration

So I am trying to provide user registration in an application using django rest framework. 因此,我正在尝试使用django rest框架在应用程序中提供用户注册。 The problem I am facing is that DRF is basically requiring that the request is authenticated 我面临的问题是DRF基本上要求对请求进行身份验证

This is the setting: 这是设置:

DEFAULT_AUTHENTICATION = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.OAuth2Authentication',
    ),
}

This is the view: 这是视图:

@permission_classes((AllowAny,))
@csrf_exempt
@api_view(['POST'])
def create_auth(request, format=None):
    data = JSONParser().parse(request)
    serialized = UserSerializer(data=data)

    if serialized.is_valid():
        user = User.objects.create_user(
            serialized.init_data['email'],
            serialized.init_data['username'],
            serialized.init_data['password'],
        )
        user.groups = serialized.init_data['groups']

        user.save()

        serialized_user = UserSerializer(user)
        return Response(serialized_user.data, status=status.HTTP_201_CREATED, headers={"Access-Control-Allow-Origin": "http://127.0.0.1:8000/"})
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST, headers={"Access-Control-Allow-Origin": "http://127.0.0.1:8000/"})

This is the test: 这是测试:

def test_user_register(self):
    user_data = {'username': 'testusername',
                 'email': "test@test.com",
                 'groups': [1],
                 'password': 'testpassword',
                 }

    resp = self.client.post("/auth/register", json.dumps(user_data), content_type="application/json")
    print resp.content

    self.assertEquals(resp.status_code, 200)
    self.assertContains(resp, user_data["username"], 1, 201)

and this is the error: 这是错误:

{"detail": "Authentication credentials were not provided."}

What am I doing wrong? 我究竟做错了什么? Isn't the decorator supposed to allow not authenticated requests? 装饰器不应该允许未经身份验证的请求吗? Even better: which is the proper way of registering users through a REST API? 甚至更好:通过REST API注册用户的正确方法是什么?

Thanks, Adi 谢谢阿迪

Check documentation here , it says: 在此处查看文档,其中显示:

...REST framework provides a set of additional decorators which can be added to your views. ... REST框架提供了一组其他装饰器,可以将其添加到视图中。 These must come after (below) the @api_view decorator. 这些必须位于@api_view装饰器之后 (下方)。

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

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