简体   繁体   English

Django模型中的Unique = True给出了IntergretyError而不是ValidationError

[英]Unique=True in Django model gives IntergretyError instead of ValidationError

I want to show a validation message like "This email is already in use" inside my html form. 我想在HTML表单中显示一条验证消息,例如“此电子邮件已在使用中”。

But I think i'm missing something. 但我认为我缺少了一些东西。 I keep getting an IntegrityError at my email field. 我在电子邮件字段中不断收到IntegrityError。 Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? 如果我在模型中使用unique = True,Django是否不应该对此进行验证并给出ValidationError? Or do I have to Try and Catch the IntegrityError myself? 还是我必须自己尝试并捕获IntegrityError?

Or maybe show me a best practice for validating unique users inside a form/model. 或向我展示验证表单/模型内唯一用户的最佳实践。

models.py models.py

class Customer(models.Model):
    FirstName = models.CharField(max_length=50)
    LastName = models.CharField(max_length=50)
    Email = models.CharField(max_length=50, unique=True, error_messages={'unique':"This email is already in use"})

views.py views.py

def customerform(request):
if request.method == 'POST':
    form = CustomerForm(request.POST)
    if form.is_valid():
        post = Customer()
        post.FirstName = form.cleaned_data['FirstName']
        post.LastName = form.cleaned_data['LastName']
        post.Email = form.cleaned_data['Email']
        post.save()
        return render(request, 'results.html', {
        'FirstName': form.cleaned_data['FirstName'],
        'Email': form.cleaned_data['Email'],})
else:        
    form = CustomerForm()
return render(request, 'form.html', {'form':form})

forms.py 表格

class CustomerForm(forms.Form):
    FirstName   = forms.CharField (label='First name:', max_length=50)
    LastName    = forms.CharField (label='Last name:', max_length=50)
    Email       = forms.EmailField(label='Email:', max_length=50)

form.html form.html

<form action="/customer/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

If you want form validation to automatically use the model attributes, you have to use a ModelForm : 如果您希望表单验证自动使用模型属性,则必须使用ModelForm

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ["FirstName", "LastName", "Email"]

If you want to use a regular Form , you need to do the validation manually. 如果要使用常规Form ,则需要手动进行验证。

def customerform(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            # first we check if email is valid
            customer = Customer.objects.filter(Email = form.cleaned_data['Email'])
            if customer.count() == 0: # email not in use
                post = Customer()
                post.FirstName = form.cleaned_data['FirstName']
                post.LastName = form.cleaned_data['LastName']
                post.Email = form.cleaned_data['Email']
                post.save()
                return render(request, 'results.html', {
                    'FirstName': form.cleaned_data['FirstName'],
                     'Email': form.cleaned_data['Email'],})
            else: # email in use so we redirect to html and we add an error message
                render(request, 'form.html', {'form':form,'error','This email is already in use'})
        else:        
            form = CustomerForm()
    return render(request, 'form.html', {'form':form})


<form action="/customer/" method="post">
    {% if error %}
        <b> {{ error }} </b> <br>
    {% endif %}
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM