django form在提交时返回null字段错误

时间:2016-07-26 16:36:32

标签: python django forms django-forms django-admin

我的django项目中有一个模型:

class Employee(models.Model):
    user = models.OneToOneField(User, related_name="EmployeeUser")
    workType = models.CharField(max_length=1)
    salary = models.IntegerField()
    Branch = models.ForeignKey(Branch)
    is_admin = models.BooleanField(default=False)

和forms.py

class EmpForm(ModelForm):
    username = fields_for_model(User)['username']
    email = fields_for_model(User)['email']
    password = fields_for_model(User)['password']
    first_name = fields_for_model(User)['first_name']
    last_name = fields_for_model(User)['last_name']
    branch = fields_for_model(Employee)['Branch']
    is_admin = fields_for_model(Employee)['is_admin']
    salary = fields_for_model(Employee)['salary']

    def __init__(self, *args, **kwargs):
        super(EmpForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Employee
        fields = []

    def save(self, commit=True):
        username = self.cleaned_data.get('username', None)
        email = self.cleaned_data.get('email', None)
        password = self.cleaned_data.get('password', None)
        first_name = self.cleaned_data.get('first_name', None)
        last_name = self.cleaned_data.get('last_name', None)
        salary = self.cleaned_data.get('salary', 0)
        branch = self.cleaned_data.get('branch', 0)
        tmp_user = User.objects.create_user(username=username, email=email, password=password, first_name=first_name,
                                        last_name=last_name)
        return Employee.objects.create(user=tmp_user, salary=0,     Branch=branch, workType='a', is_admin=False)

和我的admin.py:

class EmpAdmin(admin.ModelAdmin):
    ....
    form=EmpFrom
    def save_model(self, request, obj, form, change):
        if form.is_valid():
            obj.save()

问题在于,当我想要输入一个新员工时,在django管理员表单中它会抛出一个表单异常,即薪水字段不能为空,但我已经为它赋予了价值。 [SOLEVED] 我刚改变了:

class Meta:
        model = Employee
        fields = []

class Meta:
        model = Employee
        fields = ['first_name', 'last_name', 'username', 'password', 'branch', 'salary', 'is_admin']

并且有效

0 个答案:

没有答案