How to create user from django shell

前端 未结 7 477
借酒劲吻你
借酒劲吻你 2021-01-30 04:13

When i create user from django-admin user password\'s are encrypted . but when i create user from django shell user-pasword is saved in plain text . Example :

7条回答
  •  长发绾君心
    2021-01-30 04:26

    Answer for those using django 1.9 or greater since from django.contrib.auth.models import User has been deprecated (possibly even earlier) but definitely by 1.9.

    Instead do: in bash:

    python manage.py shell
    

    In the python shell to create a user with a password:

    from django.apps import apps
    User = apps.get_model('user', 'User')
    me = User.objects.create(first_name='john', email='johnsemail@email.com') # other_info='other_info', etc.
    me.set_password('WhateverIwant')  # this will be saved hashed and encrypted
    me.save()
    

    If coming from an API you should probably apply a Form as such:

    import json
    User = get_model('User')
    class UserEditForm(BaseModelForm):
            """This allows for validity checking..."""
    
            class Meta:
                model = User
                fields = [
                    'first_name', 'password', 'last_name',
                    'dob', # etc...
                ]
    # collect the data from the API:
    post_data = request.POST.dict()
    data = {
    'first_name': post_data['firstName'],
    'last_name': post_data['firstName'],
    'password': post_data['password'], etc.
    }
    dudette = User()  # (this is for create if its edit you can get the User by pk with User.objects.get(pk=kwargs.pk))
    form = UserEditForm(data, request.FILES, instance=dudette)
    if form.is_valid():
        dudette = form.save()
    else:
        dudette = {'success': False, 'message': unicode(form.errors)}
    return json.dumps(dudette.json())  # assumes you have a json serializer on the model called def json(self):
    

提交回复
热议问题