在Django中创建添加用户表单

Ary*_* Mz 8 django profile

我想创建一个SINGLE表单,使管理员能够创建具有扩展配置文件的新用户.请注意,我不想使用管理员和注册应用程序.我使用UserProfile模型扩展了用户.我已阅读与扩展用户配置文件相关的所有文档.但是,我真的不知道如何保存这些信息.我为此问题编写了以下django表单:

class CreateUserForm(forms.Form):
username = forms.CharField(max_length=30)
first_name = forms.CharField()
last_name = forms.CharField()
password1=forms.CharField(max_length=30,widget=forms.PasswordInput()) #render_value=False
password2=forms.CharField(max_length=30,widget=forms.PasswordInput())
email=forms.EmailField(required=False)

title = forms.ChoiceField(choices=TITLE_CHOICES)

def clean_username(self): # check if username dos not exist before
    try:
        User.objects.get(username=self.cleaned_data['username']) #get user from user model
    except User.DoesNotExist :
        return self.cleaned_data['username']

    raise forms.ValidationError("this user exist already")


def clean(self): # check if password 1 and password2 match each other
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:#check if both pass first validation
        if self.cleaned_data['password1'] != self.cleaned_data['password2']: # check if they match each other
            raise forms.ValidationError("passwords dont match each other")

    return self.cleaned_data


def save(self): # create new user
    new_user=User.objects.create_user(username=self.cleaned_data['username'],
                                    first_name=self.cleaned_data['first_name'],
                                    last_name=self.cleaned_data['last_name'],
                                    password=self.cleaned_data['password1'],
                                    email=self.cleaned_data['email'],
                                        )

    return new_user
Run Code Online (Sandbox Code Playgroud)

可以吗?但是它在first_name和last_name中给出了一个错误.说django不期望save()方法中的first_name和last_name.

小智 14

create_user仅支持用户名,电子邮件和密码参数.首先调用create_user,然后将额外的值添加到保存的对象中.

new_user=User.objects.create_user(self.cleaned_data['username'],
                                  self.cleaned_data['email'],
                                  self.cleaned_data['password1'])
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.save()
Run Code Online (Sandbox Code Playgroud)

  • 如果您指的是"公司"和"地址"等字段,则可以创建UserProfile模型,该模型与用户具有一对一的关系(https://docs.djangoproject.com/en/dev/topics/auth/ #AUTH-配置文件).这样,您可以根据需要添加任意数量的字段,并使用user.get_profile().company获取它们 (6认同)