简体   繁体   English

Django 1.8.2:将数据对象传递给User.objects.create_user

[英]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? 在Django上创建用户时,有没有办法将对象的实例(从Python)传递给create_user方法?

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: 假设我创建一个Python对象,如下所示:

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. 我试图看看是否有一种更简单的方法可以在不同的注册环境下在Django上创建用户,而不必依赖多个if-else-if子句。

(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.) (好吧,我确实尝试了在shell中实现这一点,但是我遇到了一个语法错误,并且由于命令提示符窗口的宽度仅限制为80个字符,因此很难找出它指向的是哪个字符。我在一个单独的窗口中再次尝试Python窗口外壳程序,除了我最初没有设置环境变量时遇到错误,并且因为要执行此操作而不想对它进行更改,我什至不知道设置环境变量是否仅影响命令提示符。 )

Well, as per the docs all those fields are indeed optional, and as the create_user function is: 好吧,根据文档,所有这些字段的确是可选的,并且create_user函数是:

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. 您确实可以将要设置的字典作为**extra_fields传递给该函数。 The docs for create_user are here . create_user的文档在这里 The only caveat being that email is a keyword argument. 唯一需要注意的是, email是关键字参数。

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. 您将不得不从dict中解析出可选的电子邮件,并将其作为电子邮件关键字参数传递,也可以不传递任何内容,然后将其余的内容最终转储到字典中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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