Django - пользователь должен иметь is_active = False, но в админке он отображается активным

В моем пользовательском представлении регистрации для параметра is_active пользователя установлено значение False. Для установки is_active в True используется отправленный по электронной почте авторизованный токен. Однако сразу после регистрации нового пользователя я захожу на страницу администратора как суперпользователь и вижу, что мой новый пользователь active поставил галочку

просмотров

def signup(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.is_teacher = True
            user.is_staff = True
            user.is_active = False
            to_email = form.cleaned_data.get('email')
            user.username = to_email  # make the username the same as the email
            user.save()
            group = Group.objects.get(name='teacher')
            user.groups.add(group)
            current_site = get_current_site(request)
            
            # use sendgrid api for email
            sendgrid_client = SendGridAPIClient(
                api_key=os.environ.get('SENDGRID_API_KEY'))
            from_email = From("doug@smartmark.ca")
            to_email = To(to_email)
            subject = "Activate your SmartMark Account"
            active_link = render_to_string('account/acc_active_email_link.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })

            html_text = f'Hello {user}<br/><p>Registration email</p><a href="{active_link}">{active_link}</a>'
            html_content = HtmlContent(html_text)
            mail = Mail(from_email, to_email, subject,
                        html_content)
            response = sendgrid_client.send(message=mail)

            return redirect(reverse('accounts:account_activation_sent'))
    else:
        form = CustomUserCreationForm()
    return render(request, 'account/signup.html', {'form': form})

def account_activation_sent(request):
    return render(request, 'account/account_activation_sent.html')

def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = CustomUser.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    # calls check_token function but user is already set to active - email and token
    # were never used.
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        return redirect('home')
    else:
        return render(request, 'account/account_activation_invalid.html')

Модель CustomerUser

class CustomUser(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_teacher = models.BooleanField('teacher status', default=False)

    def __str__(self):
        return self.username

Форма

class CustomUserCreationForm(UserCreationForm):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    class Meta:
        model = get_user_model()
        fields = ('email', 'first_name', 'last_name')

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

    def clean_email(self):
        value = self.cleaned_data["email"]
        if not value:
            raise forms.ValidationError('An Email address is required.')
        check_users = CustomUser.objects.filter(email__iexact=value)
        if check_users:
            raise forms.ValidationError('This email is already in use.')
        return value

Я использую встроенную аутентификацию Django. Я ожидаю, что Active в панели администратора не будет отмечен. Я также попробовал переместить user.is_active=False после user.save(), но это не изменило поведение. Я знаю из моего начального файла миграций, что по умолчанию для is_active стоит True, но я думаю, что представление регистрации будет переопределять это

Сначала я изменил сохранение формы на:

user=form.save(commit=False)

Однако, похоже, что проблема заключается в том, что когда я отправляю по электронной почте маркер авторизации, получатель электронной почты проверяет url на наличие спама. Проверяя, что url токена является действительным, токен проходит проверку. Я добавляю POST-форму, чтобы маркер не проверялся, пока пользователь не отправит форму.

Вернуться на верх