Django形成元和验证

时间:2014-11-20 14:15:29

标签: django django-forms

我有表格:

class FindAdvert(forms.ModelForm):
    class Meta:
        model = Advert
        fields = ('id', 'code')

但通过这种方式,我无法登录'因为验证返回错误:id already exist。 如何修改此表单以允许登录' (而不是注册)?

1 个答案:

答案 0 :(得分:0)

你不需要ModelForm进行登录,因为它的语义目标 - 创建|编辑数据库数据(无论如何你可以在你的视图中硬编码id - 但这是错误的方式)。< / p>

因此,使用自定义验证规则(在干净方法或视图中)创建简单Form,如下所示:

class LoginForm(forms.Form):
    username = forms.CharField(
        label=u'Username',
        required=True,
    )
    password = forms.CharField(
        label=u'Password',
        required=True,
        widget=forms.PasswordInput
    )

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()

        username = cleaned_data.get('username')
        password = cleaned_data.get('password')

        if (username and password and User.objects.filter(username=username).count() == 0)\
            or (username and password and User.objects.filter(username=username).count() == 1 and
                        User.objects.get(username=username).password != password):
            raise forms.ValidationError(u'Wrong username or password')

        return cleaned_data

<强>的观点:

from django.contrib.auth import logout, authenticate, login
from django.views.generic import FormView, RedirectView
# ... 

class LoginFormView(FormView):
    template_name = 'common/login.html'
    form_class = LoginForm

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        logout(request)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None and user.is_superuser:
            login(request, user)
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def get_success_url(self):
        return self.request.GET.get('next') or reverse('human:add')

class LogoutRedirectView(RedirectView):
    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        logout(self.request)
        return reverse('common:login')