Django 验证表单的问题

发布于 2024-11-05 23:52:57 字数 1265 浏览 1 评论 0原文

我一直试图弄清楚所有这些验证是如何工作的,但我没有掌握其中的窍门。我阅读了 djangoproject 上的很少的示例,但我缺少概念以及如何将所有内容联系在一起。

如果您可以查看我的代码并重新安排事情应该如何,以及一些解释,那就太棒了!

所以我想做一些非常简单的事情:仅使用电子邮件登录。当用户输入电子邮件时,我想检查它是否在数据库中,如果在,则登录。如果不是,我想提出一个错误“用户已在数据库中”并建议此人转到/register

所以我目前拥有的是:

view.py:

def emailLogin(request, backend, extra_context=None, initial={}):

form = EmailLoginForm(initial=initial)
if request.method == 'POST':
    form = EmailLoginForm(initial=initial, data=request.POST)
    if form.is_valid():
        user = form.do_save()

        _no_pass_login(request, user) # my custom login
        return redirect('/')

    else:
        print ('not valid')

return render_jinja(request, 'registration/email_login_form.html',
        type="register",
        form = form
        )

forms.py

class EmailLoginForm(forms.Form):
    email = forms.EmailField()
    def do_save(self):
    try:
            u = User.objects.get(email=self.cleaned_data['email'])
        except :
            raise forms.ValidationError("Already in DB")

        return u

所以重点是我缺少概念 - 应该在哪里引发验证错误,视图还是表单?它被提升到哪里?谁抓住了它?每个文件中需要导入什么内容等等。

这应该不会太困难,但我现在完全迷失了,我没有可以分析和修改我的代码以使其工作的示例,所以我在这里。

I have been trying to figure out how all this validation works, but I am not getting the hang of it. I read the very few examples on djangoproject, but I am missing concepts and how everything is tied together.

If you could please look at my code and rearrange how things should be, as well as a few explanations, that would be awesome!

So I want to do something very simple: have a login from with email ONLY. When a user types their email, i want to check if it's in the database, and if it is, login. if it is not, i want to raise an error 'user already in database' and suggest that this person goes to /register

So what i currently have is:

view.py:

def emailLogin(request, backend, extra_context=None, initial={}):

form = EmailLoginForm(initial=initial)
if request.method == 'POST':
    form = EmailLoginForm(initial=initial, data=request.POST)
    if form.is_valid():
        user = form.do_save()

        _no_pass_login(request, user) # my custom login
        return redirect('/')

    else:
        print ('not valid')

return render_jinja(request, 'registration/email_login_form.html',
        type="register",
        form = form
        )

forms.py:

class EmailLoginForm(forms.Form):
    email = forms.EmailField()
    def do_save(self):
    try:
            u = User.objects.get(email=self.cleaned_data['email'])
        except :
            raise forms.ValidationError("Already in DB")

        return u

So the whole point is that I am missing concepts - where should a validation error be raised, the view or the form? where is it raised to? who catches it? what needs to be imported in each file etc.

This shouldn't be too difficult but i am totally lost now, and i have no examples I can analyze and mod my code to work, so i am here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

菊凝晚露 2024-11-12 23:52:57

是的,您似乎确实缺少一些概念。

这种类型的表单根本不应该有保存。 is_valid() 检查的全部目的是捕获验证错误 - 因此它们应该由该调用引发。实现此目的的方法是在表单上定义clean 方法。在本例中,由于您只检查 email 字段,因此您定义了 clean_email 方法。该代码应与您当前在 do_save 中获得的代码相同。

现在,is_valid() 将返回 False。但是您的视图中需要进行一些调整才能实际显示错误。首先,将 else后移一级缩进,使其匹配 if request.method == 'POST'。现在,将第一行 - form = EmailLoginForm(initial=initial) 移动到其中,而不是 print 语句。现在,当 is_valid() 为 False 时,视图将直接进入 render_to_response,其中包含包含验证错误的已实例化表单。魔法!

Yes, you do seem to be missing some concepts.

This type of form shouldn't have a save at all. And the whole point of the is_valid() check is to catch the validation errors - so they should be raised by that call. The way to do that is to define clean methods on the form. In this case, since you're only checking the email field, you define a clean_email method. The code should be identical to what you've currently got in do_save.

Now, is_valid() will return False. But there are a couple of tweaks needed in your view to actually show the errors. First, bring that else block back one indent level, so it matches if request.method == 'POST'. Now, instead of that print statement, move the first line - form = EmailLoginForm(initial=initial) in there. Now, when is_valid() is False, the view will fall straight through to the render_to_response with an already-instantiated form containing the validation errors. Magic!

各自安好 2024-11-12 23:52:57

我认为这就是丹尼尔所说的,但如果您不确切知道发生了什么,可能会感到困惑。基本上,该表单所做的只是验证您的数据。所有的保存都是在视图中完成的。

view.py

def emailLogin(request, backend, extra_context=None, initial={}):

    form = EmailLoginForm
    if request.method == 'POST':
        form = form(initial=initial, data=request.POST)
        if form.is_valid():
            _no_pass_login(request, user) # my custom login
            return redirect('/')
        else:
            print 'Form not valid'

    else:
        form = form(initial=initial)

return render_jinja(request, 'registration/email_login_form.html',
    type="register",
    form = form
    )

forms.py

class EmailLoginForm(forms.Form):

    email = forms.EmailField()

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).count() > 0:
            raise ValidationError('User with email "%s" already exists' % email)
        return email

I think this is what Daniel was talking about, but it can be confusing if you don't know exactly what's going on. Basically, all the form does is validate your data. All the saving is done in the view.

view.py

def emailLogin(request, backend, extra_context=None, initial={}):

    form = EmailLoginForm
    if request.method == 'POST':
        form = form(initial=initial, data=request.POST)
        if form.is_valid():
            _no_pass_login(request, user) # my custom login
            return redirect('/')
        else:
            print 'Form not valid'

    else:
        form = form(initial=initial)

return render_jinja(request, 'registration/email_login_form.html',
    type="register",
    form = form
    )

forms.py

class EmailLoginForm(forms.Form):

    email = forms.EmailField()

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).count() > 0:
            raise ValidationError('User with email "%s" already exists' % email)
        return email
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文