[英]Django REST User Creation/Authentication
This question is based on the one here .这个问题是基于这里的。 I am setting up a Django REST Framework for my web app and am trying to set up User accounts.我正在为我的 web 应用程序设置 Django REST 框架并尝试设置用户帐户。 Based on the REST documentation, they put all of their account code in their example in the main project directory and a separate application so did that as well.根据 REST 文档,他们将所有帐户代码放在主项目目录中的示例中,并在一个单独的应用程序中也这样做了。 Here is what I have:这是我所拥有的:
urls.py网址.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls import url
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('users', views.UserViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
url('', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
serializers.py序列化程序.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = User
# Tuple of serialized model fields (see link [2])
fields = ( "id", "username", "password", )
views.py视图.py
from rest_framework import viewsets, permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth.models import User
from .serializers import UserSerializer
# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class CreateUserView(CreateAPIView):
model = User
permission_classes = [
permissions.AllowAny
]
serializer_class = UserSerializer
I have tried using the Boomerang REST Client in Chrome to POST data to this API, but it always returns a 403 Error saying "Invalid username/password."我曾尝试在 Chrome 中使用 Boomerang REST 客户端将数据发布到此 API,但它总是返回 403 错误,提示“用户名/密码无效”。 Specifically I am POSTing to http://127.0.0.1:8000/users/create/ with a Query String and 2 parameters: username and password.具体来说,我正在使用查询字符串和 2 个参数:用户名和密码发布到http://127.0.0.1:8000/users/create/ 。 I also tried sending it as JSON and it returned the same.我也尝试将它作为 JSON 发送,它返回相同。 Any help would be appreciated.任何帮助,将不胜感激。
It doesn't look like CreateUserView
was registered in your urls.py
.看起来CreateUserView
没有在您的urls.py
中注册。 You should be able to register it and access it normally.您应该能够注册并正常访问它。 I think this should work for you:我认为这应该适合你:
urlpatterns = [
...
url(r'^users/create/', views.CreateUserView.as_view()),
]
That said, I'd like to suggest adding an extra action for your UserViewSet
instead:也就是说,我想建议为您的UserViewSet
添加一个额外的操作:
# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated
@action(methods=['post'], detail=False, permission_classes=[permissions.AllowAny])
def register(self, request, *args, **kwargs):
# This logic was taken from the `create` on `ModelViewSet`. Alter as needed.
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Then you should be able to post via /users/register/
.然后你应该可以通过/users/register/
发布。 You can also specify your own url name and path on the decorator.您还可以在装饰器上指定自己的 url 名称和路径。
Maybe you are posting in the wrong url, try POST the same on http://127.0.0.1:8000/users/ , because ModelViewSet
adds POST, PATCH, PUT, DELETE and GET
methods automatically.也许您在错误的 url 上发布,尝试在http://127.0.0.1:8000/users/上发布相同的内容,因为ModelViewSet
会自动添加POST, PATCH, PUT, DELETE and GET
方法。
Also because you are asking for authentication ( permission_classes = [permissions.IsAuthenticated]
), you should send the headers for this in the request.另外,因为您要求进行身份验证( permission_classes = [permissions.IsAuthenticated]
),您应该在请求中发送此标头。 There is a tutorial for this in the DRF site ( https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ )在 DRF 站点中有一个教程( https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ )
based on django-rest-framework documents it's better to use viewset for create user api.基于 django-rest-framework文档,最好使用视图集创建用户 api。 therefor you need to send a POST
request to http://127.0.0.1:8000/api-auth/users and no need to CreateUserView
function.因此您需要向http://127.0.0.1:8000/api-auth/users发送POST
请求,无需CreateUserView
function。
But if you want to have a custom user create api do you need something like below:但是,如果您想让自定义用户创建 api,您是否需要以下内容:
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@action(detail=True, methods=['post'], permission_classes=[permissions.AllowAny])
def create_user(self, request, pk=None):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
To have custom serializers in your ViewSet
you can specify them in get_serializer_class
function in your ViewSet like this:要在ViewSet
中使用自定义序列化程序,您可以在get_serializer_class
function 中指定它们,如下所示:
class UserViewSet(viewsets.ModelViewSet):
# example viewset
def get_serializer_class(self):
if self.action == 'list':
return ListUserSerializer
elif self.action == 'create':
return CreateUserSerializer
elif self.action == 'update':
return UpdateUserSerializer
return DetailUserSerializer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.