如何在 Django REST 框架中注册用户? [英] How to register users in Django REST framework?
问题描述
我正在使用 Django REST 框架编写 REST API.该 API 将成为社交移动应用程序的后端.按照教程进行操作后,我可以序列化我的所有模型,并且可以创建新资源并更新它们.
I'm coding a REST API with Django REST framework. The API will be the backend of a social mobile app. After following the tutorial, I can serialise all my models and I am able to create new resources and update them.
我使用 AuthToken 进行身份验证.
I'm using AuthToken for authentication.
我的问题是:
拥有 /users
资源后,我希望应用程序用户能够注册.那么,是拥有像 /register
这样的单独资源还是允许匿名用户向 /users
发布新资源更好?
Once I have the /users
resource, I want the app user to be able to register. So, is it better to have a separate resource like /register
or allow anonymous users to POST to /users
a new resource?
另外,一些关于权限的指导会很棒.
Also, some guidance about permissions would be great.
推荐答案
我继续制作了自己的自定义视图来处理注册,因为我的序列化程序不希望显示/检索密码.我使 url 与/users 资源不同.
I went ahead and made my own custom view for handling registration since my serializer doesn't expect to show/retrieve the password. I made the url different from the /users resource.
我的网址配置:
url(r'^users/register', 'myapp.views.create_auth'),
我的观点:
@api_view(['POST'])
def create_auth(request):
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
User.objects.create_user(
serialized.init_data['email'],
serialized.init_data['username'],
serialized.init_data['password']
)
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
我可能错了,但您似乎不需要限制此视图的权限,因为您想要未经身份验证的请求......
I may be wrong, but it doesn't seem like you'll need to limit permissions on this view since you'd want unauthenticated requests ...
这篇关于如何在 Django REST 框架中注册用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!