【问题标题】:Django: "state" is an invalid keyword argument for this functionDjango:“状态”是此函数的无效关键字参数
【发布时间】:2016-01-22 19:17:07
【问题描述】:

我正在尝试在我的应用程序中添加输入,用户可以在其中输入他们的“年龄”、“城市”和“州”。它已经适用于“first_name”、“last_name”和“email”,但是当我添加这些字段时,我收到了这个错误。

人物模型:

class Person(models.Model):
    """ The model which defines a user of the application. Contains important
    information like name, email, city/state, age, etc """
    user = models.OneToOneField(User)
    first_name = models.CharField(max_length=200, null=True)
    last_name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    city = models.CharField(max_length=200, null=True)
    state = models.CharField(max_length=200, null=True)
    age = models.CharField(max_length=50, null=True)

用于创建帐户的视图:

def create_account(request):
    # function to allow a user to create their own account
    if request.method == 'POST':
        # sets a new user and gives them a username
        new_user = User(username = request.POST["username"],
                    email=request.POST["email"],
                    first_name=request.POST["first_name"],
                    last_name=request.POST["last_name"],
                    age=request.POST["age"],
                    city=request.POST["city"],
                    state=request.POST["state"])
        # sets an encrypted password
        new_user.set_password(request.POST["password"])
        new_user.save()
        # adds the new user to the database
        Person.objects.create(user=new_user,
                          first_name=str(request.POST.get("first_name")),
                          last_name=str(request.POST.get("last_name")),
                          email=str(request.POST.get("email")),
                          age=str(request.POST.get("age")),
                          city=str(request.POST.get("city")),
                          state=str(request.POST.get("state")))
        new_user.is_active = True
        new_user.save()
        return redirect('../')
    else:
        return render(request, 'polls/create_account.html')

知道为什么会出现此错误吗?

【问题讨论】:

  • 你应该在这里使用表格。

标签: python django


【解决方案1】:

User 模型中没有 state 字段,但您在创建 new_user 时尝试传递它。

【讨论】:

  • 我尝试用 Person(...) 替换 User(...) 并没有产生任何结果。我该如何解决这个问题?
  • 对不起,我不明白你的问题。您创建了一个用户,然后将该用户分配给我可以看到的 Person 对象。如何用Person 替换User?它们是 2 种不同的模型。
  • 我想一个更好的问题是,如何扩展 User 模型以具有“年龄”、“城市”和“州”等附加属性?
  • Django 有专门的文档来解释这一点:docs.djangoproject.com/en/1.9/topics/auth/customizing/…
  • 感谢您的帮助!
猜你喜欢
  • 2012-07-07
  • 2013-02-04
  • 2017-05-04
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多