简体   繁体   中英

Django 1.8.2: Passing a data object to User.objects.create_user

Is there a way you can pass an instance of object (from Python) to the create_user method when creating a user on Django?

What I mean is, suppose that I want to let the user decide whether to include a first name, a last name, both, or neither. An e-mail address is optional too.

Suppose I create a Python object as follows:

data = {first_name = 'Howdy', last_name = 'Hilary', email: 'hhilary@gmail.com}

Then I pass it as follows:

user = User.objects.create_user(username = 'jdsflsdf', password = '********', data)

Is this possible or no? I'm trying to see if there's a simpler way of creating a user on Django in different sign-up circumstances without having to rely on multiple if-else-if clauses.

(Well, I did try implementing this in the shell, except that I got a syntax error and had trouble finding out which character it was pointing to since my Command Prompt window was only limited to 80 characters in width. I tried again in a separate Python window shell, except I got an error for not setting the Environment Variable initially, and did not want to make a change to it because it's so delicate to do. I don't even know if setting Environment Variables only affects the Command Prompt.)

Well, as per the docs all those fields are indeed optional, and as the create_user function is:

create_user(username, email=None, password=None, **extra_fields)

You can indeed pass a dictionary to that function as **extra_fields with the ones you want to set. The docs for create_user are here . The only caveat being that email is a keyword argument.

You would have to parse out the optional email from the dict, and pass either it or none in as the email keyword argument, and then dump the rest in in the dictionary at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM