无法从浏览器(DJANGO)上的ModelForm引发验证错误

时间:2019-03-25 02:49:57

标签: django forms django-forms modelform validationerror

我正在尝试引发一个错误,如果用户输入提交数据库中已经存在的电子邮件,则会在浏览器中显示该错误。由于某些原因,不是引发错误,而是什么都没有保存在数据库中,而是将用户重定向到我设置为重定向到的页面。

如果数据库中存在电子邮件,我希望能够阻止用户并引发错误。

型号:

class Foo(models.Model):
    full_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50, blank=False)
    phone_number = models.CharField(max_length=10, blank=False)

表格。

from django import forms

from .models import Foo

class FooModelForm(ModelForm):
    class Meta:
        model = Foo
        fields = ['full_name', 
                'email',
                'phone_number']
        help_texts = {'full_name': ('Required'),
                    'email': ('Required'),
                    'phone_number': ('Required')}

    def clean_email(self):
        '''
        Check if exists in database.
        '''
        email = self.cleaned_data.get('email')
        try:
            match = Foo.objects.get(email=email)
        except Foo.DoesNotExist:
            return email

        # raise forms.ValidationError('This email is already in use.')

from django.shortcuts import render, redirect
from snippets.models import Foo
from snippets.forms import FooModelForm



def index(request):
    if request.method == 'POST':
        form = FooModelForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect('snippets:form-sent')

    else:
        form = FooModelForm()

    context = {'form':form}
    return render(request, 'snippets/index.html', context)  

HTML

<form method="post" id="form">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="text-center">
       <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>

我在这里尽可能地迷失了。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

你快到了!只需按照下面的代码段

from django import forms
from .models import Foo


class FooModelForm(ModelForm):
    class Meta:
        model = Foo
        fields = ['full_name',
                  'email',
                  'phone_number']
        help_texts = {'full_name': ('Required'),
                      'email': ('Required'),
                      'phone_number': ('Required')}

    def clean_email(self):
        '''
        Check if exists in database.
        '''
        email = self.cleaned_data.get('email')
        if Foo.objects.filter(email=email).exists():
            return email
        else:
            raise forms.ValidationError('This email is already in use.')


为什么我要在 exists() 上使用 try...except 方法?

try..except更快,更高效。
参考What is more efficient .objects.filter().exists() or get() wrapped on a try

答案 1 :(得分:1)

您有一个简单的缩进问题。即使表单无效,您的return redirect...行也总是在POST上调用。再将其缩进一个缩进量,使其位于is_valid块内。