【发布时间】:2016-09-13 21:46:29
【问题描述】:
我在 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)。
是否可以进行这种重定向?
谢谢!
【问题讨论】:
-
view 负责返回 HTTP 响应(包括重定向)。表单负责处理输入数据。它们不返回响应,因此您无法从表单内部重定向。
-
视图如何知道是否应该重定向或其他什么?我应该从表单中返回什么?
标签: python django django-forms django-views