django休息框架用户注册 [英] django rest framework user registration
问题描述
所以我试图使用django休息框架在应用程序中提供用户注册。我遇到的问题是DRF基本上要求该请求进行身份验证
So I am trying to provide user registration in an application using django rest framework. The problem I am facing is that DRF is basically requiring that the request is authenticated
这是设置:
DEFAULT_AUTHENTICATION = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.OAuth2Authentication',
),
}
这是视图:
@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/"})
这是测试:
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)
这是t他错误:
{"detail": "Authentication credentials were not provided."}
我做错了什么?不是装饰器不允许没有验证的请求吗?
更好:哪个是通过REST API注册用户的正确方式?
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?
谢谢,
Adi
Thanks, Adi
推荐答案
检查文档这里,它说:
... REST框架提供了一套额外的装饰器,将
添加到您的意见。 这些必须来自 (以下)@api_view
装饰器。
...REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator.
这篇关于django休息框架用户注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!