将first_name,last_name传递给User.objects.create_user()Django

时间:2019-01-18 19:51:36

标签: python django

我正在尝试使用他们的名字,姓氏,用户名,电子邮件和密码注册用户。我在Django文档的create_user中看到,first_name和last_name包含在用户模型的默认字段中。但是,当我尝试提交注册表时,出现一条错误消息,提示 “ create_user()需要2到4个位置参数,但给出了6个位置参数” 。我的代码有什么问题?

无论如何,可以在不创建自定义用户模型的情况下解决此问题? 如何将first_name和last_name传递给create_user()?

forms.py:

from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()

class RegisterForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    username = forms.CharField()
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data.get('username')
        qs = User.objects.filter(username=username)
        if qs.exists():
            raise forms.ValidationError("Username is taken")
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("email is taken")
        return email

    def clean(self):
        data = self.cleaned_data
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password2 != password:
            raise forms.ValidationError("Passwords must match.")
        return data

views.py:

from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponse
from django.shortcuts import render, redirect

from .forms import LoginForm, RegisterForm

User = get_user_model()

def register_page(request):
    register_form = RegisterForm(request.POST or None)
    context = {
        "register_form": register_form
    }

    if register_form.is_valid():
        username = register_form.cleaned_data.get("username")
        first_name = register_form.cleaned_data.get("first_name")
        last_name = register_form.cleaned_data.get("last_name")
        email = register_form.cleaned_data.get("email")
        password = register_form.cleaned_data.get("password")

        new_user = User.objects.create_user(username, email, password, first_name, last_name)

    return render(request, "auth/register.html", context)

2 个答案:

答案 0 :(得分:2)

您需要将它们作为关键字参数传递,以便它具有与值对应的字段的名称。

new_user = User.objects.create_user(
    username, email, password, 
    first_name=first_name,
    last_name=last_name,
)

答案 1 :(得分:0)

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

**extra_fields ar关键字参数意味着您应将它们作为first_name=first_name传递

阅读此内容可能会有所帮助: https://docs.djangoproject.com/en/2.1/ref/contrib/auth/#django.contrib.auth.models.User