Django - 从表单的干净方法重定向

时间:2016-05-17 16:49:28

标签: python django django-forms django-views

我在django有一个登录表单,我需要在我的clean方法中做一些额外的检查:

class LoginForm(BootstrapFormMixin, forms.Form):
    email = forms.EmailField(required=True, max_length=30)
    password = forms.CharField(required=True, widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = self.__class__.__name__.lower()
        self.helper.form_action = ''

        self.helper.layout = Layout(
            Field('email'),
            Field('password'),
            Div(
                Submit('submit', _('Login'),
                       css_class="btn btn-block btn-success"),
                css_class=''
            )
        )

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        user = authenticate(email=email, password=password)
        if user:
            company = user.company
            if not company.is_active:
                # here I want to make a redirect; if is it possible to add a flash message it would be perfect!
                raise forms.ValidationError(_('Account activation is not finished yet'))
        else:
            raise forms.ValidationError(_('Invalid credentials'))
        return self.cleaned_data

它工作正常,但是当凭据正确时,但是名为company的用户相关对象不活动(is_active = False)我想将用户重定向到另一个视图并添加一些flash消息(可能使用django.contrib.messages)。

是否可以进行此类重定向?

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以在表单中添加一个布尔Fetching package metadata: .... Solving package specifications: . Error: Package missing in current osx-64 channels: - awscli You can search for this package on anaconda.org with anaconda search -t conda awscli You may need to install the anaconda-client command line client with conda install anaconda-client 属性,以了解何时进行重定向:

redirect

答案 1 :(得分:0)

您可以在表单中引发验证错误时指定特定的错误代码。

def clean(self):
        ...
        if not company.is_active:
            # here I want to make a redirect; if is it possible to add a flash message it would be perfect!
            raise forms.ValidationError(_('Account activation is not finished yet'), code='inactive')

然后,在视图中,您可以检查错误代码,并在适当时重定向。您可以使用form.errors.as_data()检查错误代码。由于您在ValidationError方法中引发了clean,因此该错误不属于特定字段,因此您可以使用__all__密钥进行访问。

if form.is_valid():
    # login user then redirect
else:
    for error in form.errors.as_data()['__all__']:
        if error.code == 'inactive':
            messages.warning(request, 'Account is inactive')
            return redirect('/other-url/')
    # handle other errors as normal

答案 2 :(得分:0)

因此,我想冒险猜测您仍然希望在重定向用户之前将用户置于FIRST中。

如果上述情况属实,请先完成表单的PRIMARY功能。

重定向可以在"视图"在您可以重定向用户之前,首先需要运行用户登录功能。在此之前,无需再运行其他验证。

以下是我为视图编写代码段的方法 - 仅显示与重定向相关的步骤(而不是整个视图)。假设主页:索引'登录后将用户路由到正常的重定向页面'公司:add_company_info'使用消息将用户路由到异常页面。

if form.is_valid():
    user = form.login(request) # assume this form function calls django authenticate and will return the user if successful
    if user:
        login(request, user)
        if user.company.is_active: # this is assuming the user.company relationship exists
            return redirect('home:index')
        else:
            messages.add_message(request, messages.INFO, "Please fill in your company information")
            return redirect('company:add_company_info')