我不能在django.contrib.auth.models的用户模型中添加一些列吗?

时间:2017-11-23 01:42:32

标签: python django

我想添加生日&性别数据列到django.contrib.auth.models的用户模型。但是,我写了forms.py之类的

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User

class RegisterForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email','password1','password1','birthday','sex',)
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'
        self.fields['birthday'].widget.attrs['class'] = 'form-control'
        self.fields['sex'].widget.attrs['class'] = 'form-control'

当我运行代码时,会发生django.core.exceptions.FieldError:为用户错误指定的未知字段(生日)。 我搜索了Django文档,所以我找到了各种User对象'字段仅限用户名和&电子邮件&密码& is_staff& last_login等。但现在我想添加生日&性别数据栏,我怎么能这样做?我不能这样做吗?我该怎么写呢? 现在通过回答,我重写了models.py

from django.db import models
from django.contrib.auth.models import User

class NewUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birthday = models.DateField()
    sex = models.IntegerField()

我重写了forms.py

class RegisterForm(ModelForm):
    class Meta:
        model = NewUser
        fields = ('username', 'email','password1','password1','birthday',)
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'
        self.fields['birthday'].widget.attrs['class'] = 'form-control'

我之前以同样的方式重写了forms.py。但是我收到了一个错误django.core.exceptions.FieldError:为NewUser指定的未知字段(用户名,密码1,电子邮件)。我应该如何解决这个问题? / p>

1 个答案:

答案 0 :(得分:0)

更新

RegisterForm中,model应为NewUser,您可能希望使用ModelForm

Creating forms from models

原单

仅更改form是不够的,您需要从model开始,我建议您使用OneToOneField并将您想要的内容添加到您自己的model

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    birthday = models.DateField()
    sex = models.IntegerField()

然后您可以创建自己的form

Extending the existing User model