How to create a django User using DRF's ModelS

2019-04-26 16:15发布

In django, creating a User has a different and unique flow from the usual Model instance creation. You need to call create_user() which is a method of BaseUserManager.

Since django REST framework's flow is to do restore_object() and then save_object(), it's not possible to simply create Users using a ModelSerializer in a generic create API endpoint, without hacking you way through.

What would be a clean way to solve this? or at least get it working using django's built-in piping?

Edit:

Important to note that what's specifically not working is that once you try to authenticate the created user instance using django.contrib.auth.authenticate it fails if the instance was simply created using User.objects.create() and not .create_user().

4条回答
狗以群分
2楼-- · 2019-04-26 16:26

Another way to fix this is to overwrite pre_save(self, obj) method in your extension of viewsets.GenericViewSet like so:

def pre_save(self, obj):
    """ We have to encode the password in the user object that will be
    saved before saving it.
    """
    viewsets.GenericViewSet.pre_save(self, obj)
    # Password is raw right now, so set it properly (encoded password will
    # overwrite the raw one then).
    obj.user.set_password(obj.user.password)

Edit:

Note that the obj in the code above contains the instance of User class. If you use Django's user model class directly, replace obj.user with obj in the code (the last line in 2 places).

查看更多
别忘想泡老子
3楼-- · 2019-04-26 16:37

It seems like you should be overriding restore_object() in your serializer, not save(). This will allow you to create your object correctly.

However, it looks like you are trying to abuse the framework -- you are trying to make a single create() create two objects (the user and the profile). I am no DRF expert, but I suspect this may cause some problems.

You would probably do better by using a custom user model (which would also include the profile in the same object).

查看更多
对你真心纯属浪费
4楼-- · 2019-04-26 16:38

Eventually I've overridden the serializer's restore_object method and made sure that the password being sent is then processes using instance.set_password(password), like so:

def restore_object(self, attrs, instance=None):
    if not instance:
        instance = super(RegisterationSerializer, self).restore_object(attrs, instance)
    instance.set_password(attrs.get('password'))
    return instance

Thanks everyone for help!

查看更多
Juvenile、少年°
5楼-- · 2019-04-26 16:46

I'm working with DRF. And here is how I create users:

I have a Serializer with overrided save method:

def save(self, **kwargs ):
    try:
        user = create_new_user(self.init_data)
    except UserDataValidationError as e:
        raise FormValidationFailed(e.form)
    self.object = user.user_profile
    return self.object

create_new_user is just my function for user creation and in the view, I just have:

def post(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs)
查看更多
登录 后发表回答