1

由于许多细节会使这篇文章变得太长,我正在使用自定义用户模型,以及 django-registration 和 Guardian。

一切都很好,但我正在努力让每个注册的用户都自动设置为活动状态,所以“他们”(现在只有我在模拟用户)可以立即登录。到目前为止,我所做的方法是在 SQL 表中将该字段手动设置为“1”(真)。

似乎无论我如何安排事情,is_active标志总是False直到我在 SQL 中手动更改它,即使我将它打印到我的控制台并且在我注册时它显示 True。

确实user.save()通过更改为 来让它工作user.save(commit=True),这确实会生成is_active标志True并允许用户登录,但它总是会抛出一个错误,上面写着:

类型错误:save() 得到了一个意外的关键字参数“提交”

当然,这都是为了测试目的,我确实打算引入电子邮件验证,但我对为什么我不能简单地设置标志和save().

这是我的register/forms.py

class GeneralUserForm(UserCreationForm):
    business_name = forms.CharField(required=True)

    class Meta:
        model = GeneralUser
        fields = ['username', 'email', 'password1',
                  'password2', 'business_name']

    # TODO: only create all objects if no error is found
    def save(self, commit=True):
        user = super(GeneralUserForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])

        # TODO: create permissions, including groups.
        if commit:
            user.is_active = True  # remove before deployment
            print(user.is_active)
            user.save() # LINE I CHANGED
            business = Business.objects.create(name=self.cleaned_data['business_name'], owner=user)
            business.save()
            mng_grp = create_perms_for_biz(business, user)
            user.groups.add(mng_grp)
        return user

我的register/models.py

class GeneralUser(AbstractUser, GuardianUserMixin):

    username = models.CharField(
        ('username'),
        max_length=150,
        unique=True,
        help_text=('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        error_messages={
            'unique': ("A user with that username already exists."),
        },
    )
    password = models.CharField(max_length=100)
    email = models.EmailField(('email address'), blank=True)

    is_active = models.BooleanField(
        ('active'),
        default=True,
        help_text=(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    objects = UserManager()

    date_joined = models.DateTimeField(('date joined'), default=timezone.now)
    business_name = models.CharField(('business name'), max_length=150, blank=True)

    USERNAME_FIELD = 'username'


    def email_user(self, subject, message, from_email=None, **kwargs):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email], **kwargs)


def get_custom_anon_user(User):
    return User(
        username='AnonymousUser',
    )
4

1 回答 1

0

您将ModelForm.save()方法与不带commit参数的Model.save()方法混淆了。

于 2018-02-23T08:26:05.097 回答