簡體   English   中英

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

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

我想在HTML表單中顯示一條驗證消息,例如“此電子郵件已在使用中”。

但我認為我缺少了一些東西。 我在電子郵件字段中不斷收到IntegrityError。 如果我在模型中使用unique = True,Django是否不應該對此進行驗證並給出ValidationError? 還是我必須自己嘗試並捕獲IntegrityError?

或向我展示驗證表單/模型內唯一用戶的最佳實踐。

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

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})

表格

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 action="/customer/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

如果您希望表單驗證自動使用模型屬性,則必須使用ModelForm

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

如果要使用常規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