1048, «Столбец ‘last_name’ не может быть нулевым» Django AbstractUser

#django #django-authentication #django-auth-models

#django #django-аутентификация #django-auth-models

Вопрос:

Я пытаюсь создать регистрацию для каждой новой учетной записи, используя UserCreationForm из формы в CreateView общие представления на основе классов из представлений, из моей настраиваемой модели аутентификации, используя AbstractUser , но каждый раз, когда я отправляю форму, она выдает мне эту ошибку:

 1048, "Column 'last_name' cannot be null"
 

Но я уже заполняю last_name input

вот мои взгляды на создание учетной записи:

 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
 

Ответ №1:

Вы не возвращаете данные из clean_last_name следовательно ошибка

 def clean_last_name(self):
    ....
    return data
 

Комментарии:

1. выдумка! да, я забыл! только из-за этого я уже запутался, я никогда не смотрю на свой код внимательно! ну что ж, большое спасибо!