无法分配无:“StaffMember.user”不允许空值

时间:2014-04-10 11:27:20

标签: python django

好的,这是代码,我将在页面底部解释我尝试做的事情。我刚刚开始使用python和django,请记住这一点。

Models.py(这里有更多,但不重要):

STAFF_TYPES = (
    ('OG', _('Organizer')),
    ('MO', _('Moderator')),
    ('SC', _('Scanner'))
)

class StaffMember(models.Model):
    """
        Staff member class
    """

    user = models.ForeignKey(User, verbose_name=_('user'))
    staff_type = models.CharField(
        max_length=3,
        choices=STAFF_TYPES,
        verbose_name=_('staff type')
    )

forms.py:

class StaffMemberForm(forms.ModelForm):
    user = forms.ModelChoiceField(User.objects.all(), label=_('User'), required=False)
    username = forms.CharField(label=_('Username'), required=False)
    first_name = forms.CharField(label=_('First name'), required=False)
    last_name = forms.CharField(label=_('Last name'), required=False)
    email = forms.EmailField(label=_('Email'), required=False)

    def passwordRandom(string_length=10):
        random = str(uuid.uuid4())
        random = random.upper()
        random = random.replace("-", "")
        return random[0:string_length]

    class Meta:
        model = StaffMember
        fields = ('staff_type',)

    def clean(self):
        if self.errors:
            return self.cleaned_data

        super(StaffMemberForm, self).clean()
        cleaned_data = self.cleaned_data
        username = cleaned_data.get("username")
        first_name = cleaned_data.get("first_name")
        last_name = cleaned_data.get("last_name")
        email = cleaned_data.get("email")
        user = cleaned_data.get("user")
        staff_type = cleaned_data.get("staff_type")
        check = [username, user]
        if staff_type:
            if any(check) and not all(check):
                return cleaned_data
        raise forms.ValidationError(_('Choose a user from the dropdown OR make a new user'))

    def save(self, commit=True):
        if self.cleaned_data.get("user") is None:
            User.username = self.cleaned_data['username']
            User.first_name = self.cleaned_data['first_name']
            User.last_name = self.cleaned_data['last_name']
            User.email = self.cleaned_data['email']
            User.password = self.passwordRandom(8)
            StaffMember.user = User
            User.save()
        else:
            StaffMember.user = self.cleaned_data.get("user")
        StaffMember.save()

好吧,基本上我在这里尝试做的是创建选项,从下拉列表中选择现有用户或使用表单创建一个,因此不能使用这些字段,因为它们都可以为空(虽然不是在同一时间)。 因此,我希望表单能够保存新用户,并在他们选择创建新用户时使用该用户连接到该员工。我该怎么做才是因为到目前为止我只是犯了一个错误。

提前致谢, 亚伦

PS。对不起凌乱的代码,就像我之前所说的那样

1 个答案:

答案 0 :(得分:2)

您需要在User方法

中创建新的save()对象
def save(self, commit=True):
    # Run the default save method, commit=False stops the
    # model saving to the db
    staff_member = super(StaffMemberForm, self).save(commit=False)

    if self.cleaned_data.get("user") is None:
        # Create a new User object
        user = User()
        user.username = self.cleaned_data['username']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']
        user.password = self.passwordRandom(8)

        # Save new user
        user.save()

        # Apply the new user to the staff_member object
        staff_member.user = user

    else:
        staff_member.user = self.cleaned_data.get("user")

    # If the form was expecting to save the StaffMember then save
    if commit:
        staff_member.save()

    return staff_member

更新:修改代码以反映评论