【问题标题】:TypeError at /users/sigup create_user() takes from 2 to 4 positional arguments but 5 were given/users/sigup create_user() 的 TypeError 采用 2 到 4 个位置参数,但给出了 5 个
【发布时间】:2020-01-25 08:09:59
【问题描述】:

我的模型有用户名、生日、语言、货币等...

我让客人在尝试注册时需要填写用户名、电子邮件、密码(必需)和生日(可选)。但发生错误。

/users/sigup 处的类型错误 create_user() 接受 2 到 4 个位置参数,但给出了 5 个

models.py

username = models.CharField(max_length=10, blank=False, unique=True)
language = models.CharField(
    choices=LANGUAGE_CHOICES, max_length=2, blank=True, default=LANGUAGE_KOREAN)
currency = models.CharField(
    choices=CURRENCY_CHOICES, max_length=2, blank=True, default=CURRENCY_KOREA)
birthdate = models.DateField(blank=True, null=True)
login_method = models.CharField(
    max_length=50, choices=LOGIN_CHOICES, default=LOGIN_EMAIL)

forms.py

def save(self):
    username = self.cleaned_data.get("username")
    email = self.cleaned_data.get("email")
    password = self.cleaned_data.get("password")
    birthdate = self.cleaned_data.get("birthdate")
    user = models.User.objects.create_user(
        username, email, password, birthdate)
    user.save()

views.py

   class SignUpView(FormView):
        template_name = "users/signup.html"
        form_class = forms.SignUpForm
        success_url = reverse_lazy("cores:home")

        def form_valid(self, form):
            form.save()
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            birthdate = self.cleaned_data.get("birthdate")
            user = authenticate(self.request, email=email, password=password)
            if user is not None:
                login(self.request, user)
            return super().form_valid(form)

想用电子邮件和密码来访客登录,但我怎样才能实现呢?

【问题讨论】:

  • 显示models.py的正确内容

标签: python django


【解决方案1】:

生日应该作为关键字参数传递:

user = models.User.objects.create_user(username, email, password, birthdate=birthdate)

因为create_user() 只接受用户名、电子邮件、密码作为位置参数。任何其他附加参数都应该是关键字参数。

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2022-12-12
    • 1970-01-01
    • 2021-06-28
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多