Django:手动设置is_active = True,没办法?

时间:2017-10-20 21:15:11

标签: python django django-registration django-guardian

由于一系列原因,详细说明会使这篇文章过长,我使用自定义用户模型,django-registration和监护人。

一切都运行得很好,但是我试图做到这一点,所以每个注册的用户都会自动设置为活动状态,所以"他们" (现在它只有我模仿用户)可以立即登录。到目前为止我的方法是手动将该字段设置为" 1" (True)在SQL表中。

似乎无论我如何安排,is_active标志始终为False,直到我在SQL中手动更改它,即使我将其打印到我的控制台并且&# 39;我注册时显示为True。

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

  

TypeError:save()得到了一个意外的关键字参数' commit'

当然,这完全是出于测试目的而 我做 打算引入电子邮件验证,但我对我为什么非常感兴趣无法简单地设置标记和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',
    )

1 个答案:

答案 0 :(得分:0)

您感到困惑的ModelForm.save()方法会将commit参数与Model.save()方法相提并论。