0

我正在尝试使用UserCreationForm从表单到视图中的基于CreateView类的视图泛型为每个新帐户创建一个注册,从我的自定义身份验证模型使用AbstractUser但每次提交它都会给我这个错误:

1048, "Column 'last_name' cannot be null"

但是我已经填写了last_nameinput

这是我对创建帐户的看法:

class AccountCreateView(LoginRequiredMixin, CreateView):
    template_name = 'components/crud/form.html'
    form_class    = AccountForm

    def get_context_data(self, **kwargs):
        kwargs['context_title']        = 'New Account'
        kwargs['context_icon']         = '<em class="fa fa-plus"></em>'
        kwargs['context_button_title'] = 'Create Account'
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        print(self.request.POST.get('last_name'))
        try:
            self.object = form.save()
            messages.success(self.request, '<em class="fa fa-check"></em> Account created!')
        except IntegrityError as e:
            messages.error(self.request, f'<em class="fa fa-exclamation"></em> {e}')
            return self.form_invalid(form)
        return super().form_valid(form)

    def form_invalid(self, form):
        return super().form_invalid(form)

    def get_success_url(self):
        return reverse_lazy('apps:newaccount')

这是表格:

class AccountForm(UserCreationForm):

    def clean_first_name(self):
        data = self.cleaned_data.get('first_name')
        if data == '':
            raise forms.ValidationError(_('What\'s your name?'))
        return data

    def clean_last_name(self):
        data = self.cleaned_data.get('last_name')
        if data == '':
            raise forms.ValidationError(_('What\'s your last name?'))

    def clean_email(self):
        data = self.cleaned_data.get('email')
        if data == '':
            raise forms.ValidationError(_('What\'s was the email address for this account?'))
        return data

    def clean_username(self):
        data = self.cleaned_data.get('username')
        if data == '':
            raise forms.ValidationError(_('Provide your username.'))
        return data

    def __init__(self, *args, **kwargs):
        super(AccountForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.pop('autofocus', None)
        self.fields['first_name'].widget.attrs.update({
            'autofocus': True
        })
        for field in self.fields:
            self.fields[field].required = False
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
            })

    class Meta(UserCreationForm.Meta):
        model  = Users
        fields = ('first_name', 'last_name', 'email', 'user_type', ) + UserCreationForm.Meta.fields

请注意,我已经AUTH_USER_MODEL进行了设置,并且可以使用它来登录一些已经在由此生成的身份验证模型中注册的帐户:

python manage.py createsuperuser
4

1 回答 1

1

您没有从clean_last_name错误中返回数据

def clean_last_name(self):
    ....
    return data
于 2020-12-25T15:03:56.100 回答