97

我正在使用Django REST framework编写一个 REST API 。API 将成为社交移动应用程序的后端。按照教程完成后,我可以序列化所有模型,并且可以创建新资源并更新它们。

我正在使用 AuthToken 进行身份验证。

我的问题是:

获得/users资源后,我希望应用用户能够注册。那么,拥有一个单独的资源是否更好,/register或者允许匿名用户发布到/users新资源?

此外,有关权限的一些指导会很棒。

4

11 回答 11

116

Django REST Framework 3允许序列化程序中的覆盖create方法:

from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model

UserModel = get_user_model()


class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)

    def create(self, validated_data):

        user = UserModel.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
        )

        return user

    class Meta:
        model = UserModel
        # Tuple of serialized model fields (see link [2])
        fields = ( "id", "username", "password", )

继承自的类的序列化字段ModelSerializer必须在MetaDjango Rest Framework v3.5和最新版本中明确声明。

文件api.py

from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model # If used custom user model

from .serializers import UserSerializer


class CreateUserView(CreateAPIView):

    model = get_user_model()
    permission_classes = [
        permissions.AllowAny # Or anon users can't register
    ]
    serializer_class = UserSerializer
于 2015-04-01T12:41:25.210 回答
53

我继续制作自己的自定义视图来处理注册,因为我的序列化程序不希望显示/检索密码。我使 url 与 /users 资源不同。

我的网址配置:

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)

我可能错了,但您似乎不需要限制此视图的权限,因为您想要未经身份验证的请求......

于 2013-07-19T15:12:13.023 回答
48

最简单的解决方案,在 DRF 3.x 中工作:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'email', 'first_name', 'last_name')
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name']
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

无需其他更改,只需确保未经身份验证的用户具有创建新用户对象的权限即可。

write_only_fields将确保不显示密码(实际上是我们存储的哈希值),而覆盖create方法确保密码不是以明文形式存储,而是作为哈希值存储。

于 2015-04-25T16:19:55.797 回答
36

我通常像对待任何其他需要授权的 API 端点一样对待用户视图,除了我只是用我自己的 POST(又名创建)覆盖视图类的权限集。我通常使用这种模式:

from django.contrib.auth import get_user_model
from rest_framework import viewsets
from rest_framework.permissions import AllowAny


class UserViewSet(viewsets.ModelViewSet):
    queryset = get_user_model().objects
    serializer_class = UserSerializer

    def get_permissions(self):
        if self.request.method == 'POST':
            self.permission_classes = (AllowAny,)

        return super(UserViewSet, self).get_permissions()

为了更好地衡量,这是我通常使用的序列化程序:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = (
            'id',
            'username',
            'password',
            'email',
            ...,
        )
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        user = get_user_model().objects.create_user(**validated_data)
        return user

    def update(self, instance, validated_data):
        if 'password' in validated_data:
            password = validated_data.pop('password')
            instance.set_password(password)
        return super(UserSerializer, self).update(instance, validated_data)

djangorestframework 3.3.x / Django 1.8.x

于 2015-12-23T03:21:10.377 回答
27

我更新了 Cahlan 的答案以支持来自 Django 1.5 的自定义用户模型,并在响应中返回用户的 ID。

from django.contrib.auth import get_user_model

from rest_framework import status, serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()

@api_view(['POST'])
def register(request):
    VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
    DEFAULTS = {
        # you can define any defaults that you would like for the user, here
    }
    serialized = UserSerializer(data=request.DATA)
    if serialized.is_valid():
        user_data = {field: data for (field, data) in request.DATA.items() if field in VALID_USER_FIELDS}
        user_data.update(DEFAULTS)
        user = get_user_model().objects.create_user(
            **user_data
        )
        return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
于 2013-10-12T17:56:48.073 回答
16

上面的@cpury 建议使用write_only_fields选项。然而,这在 DRF 3.3.3 中对我不起作用

DRF 3.0中,ModelSerializer 上的write_only_fields选项已移至 PendingDeprecation,在DRF 3.2中,替换为更通用的 extra_kwargs:

extra_kwargs = {'password': {'write_only': True}}

于 2016-04-27T22:34:14.643 回答
10

到目前为止,所有答案都创建了用户,然后更新了用户的密码。这会导致两次数据库写入。为避免额外不必要的数据库写入,请在保存之前设置用户密码:

from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):

    class Meta:
        model = User

    def create(self, validated_data):
        user = User(**validated_data)
        # Hash the user's password.
        user.set_password(validated_data['password'])
        user.save()
        return user
于 2016-07-14T18:50:54.213 回答
5

基于 Python 3、Django 2 和 Django REST Framework 视图集的实现:

文件:serializers.py

from rest_framework.serializers import ModelSerializers
from django.contrib.auth import get_user_model

UserModel = get_user_model()

class UserSerializer(ModelSerializer):
    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        user = UserModel.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
        )
        return user

    class Meta:
        model = UserModel
        fields = ('password', 'username', 'first_name', 'last_name',)

文件views.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from django.contrib.auth import get_user_model
from .serializers import UserSerializer

class CreateUserView(CreateModelMixin, GenericViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer

文件urls.py

from rest_framework.routers import DefaultRouter
from .views import CreateUserView

router = DefaultRouter()
router.register(r'createuser', CreateUserView)

urlpatterns = router.urls
于 2019-01-23T16:56:18.120 回答
5

聚会有点晚了,但可能会帮助不想编写更多代码行的人。

我们可以使用该super方法来实现这一点。

class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(
          write_only=True,
    )

    class Meta:
       model = User
       fields = ('password', 'username', 'first_name', 'last_name',)

    def create(self, validated_data):
        user = super(UserSerializer, self).create(validated_data)
        if 'password' in validated_data:
              user.set_password(validated_data['password'])
              user.save()
        return user
于 2016-01-23T08:41:12.090 回答
2

虽然这个问题有很多答案,但没有一个答案(截至我撰写本文时)解决了关键的安全问题,即settings.AUTH_PASSWORD_VALIDATORS. 因此,可以创建一个'1'不能接受的密码。所以我已经解决了这个主要的安全问题。这是我的解决方案:

在 serializers.py 中:

from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers


class SignupSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ['username', 'first_name', 'last_name', 'email', 'password', ]
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate_password(self, value):
        validate_password(value)
        return value

    def create(self, validated_data):
        user = get_user_model()(**validated_data)

        user.set_password(validated_data['password'])
        user.save()

        return user

在views.py中:

from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated

from . import forms, serializers


class SignupViewSet(mixins.CreateModelMixin,
                    viewsets.GenericViewSet):
    permission_classes = [AllowAny]
    serializer_class = serializers.SignupSerializer

API 响应:

现在,如果您尝试使用简单的密码,如'1',将自动返回此响应:

{
    "password": [
        "This password is too short. It must contain at least 8 characters.",
        "This password is too common.",
        "This password is entirely numeric."
    ]
}

如果密码像'12345678',则响应为:

{
    "password": [
        "This password is too common.",
        "This password is entirely numeric."
    ]
}

这样,终端客户端将确切地知道密码有效还需要什么。

于 2021-03-28T16:27:53.717 回答
0
# This work nicely, but serializer will reamain as it is, like

from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers


class SignupSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ['username', 'first_name', 'last_name', 'email', 'password', ]
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate_password(self, value):
        validate_password(value)
        return value

    def create(self, validated_data):
        user = get_user_model()(**validated_data)

        user.set_password(validated_data['password'])
        user.save()

        return user

为了简化,将您的视图修改为

from rest_framework import mixins, viewsets

from rest_framework.permissions import AllowAny, IsAuthenticated

from . import forms, serializers
class SignUpUserView(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [AllowAny]
    queryset = get_user_model().objects.all() #Add this line
    serializer_class = SignUpSerializer
于 2021-09-05T07:50:28.683 回答