Unique=True in Django model gives IntergretyError instead of ValidationError












0














I want to show a validation message like "This email is already in use" inside my html form.



But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself?



Or maybe show me a best practice for validating unique users inside a form/model.



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


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









share|improve this question






















  • I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
    – Robin Zigmond
    Nov 20 at 18:39










  • It doesn't look like your form has a clean_Email() method. That would be a good place to start.
    – John Gordon
    Nov 20 at 18:55


















0














I want to show a validation message like "This email is already in use" inside my html form.



But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself?



Or maybe show me a best practice for validating unique users inside a form/model.



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


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









share|improve this question






















  • I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
    – Robin Zigmond
    Nov 20 at 18:39










  • It doesn't look like your form has a clean_Email() method. That would be a good place to start.
    – John Gordon
    Nov 20 at 18:55
















0












0








0







I want to show a validation message like "This email is already in use" inside my html form.



But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself?



Or maybe show me a best practice for validating unique users inside a form/model.



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


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









share|improve this question













I want to show a validation message like "This email is already in use" inside my html form.



But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself?



Or maybe show me a best practice for validating unique users inside a form/model.



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


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






python django sqlite3






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 18:28









Wessel

84




84












  • I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
    – Robin Zigmond
    Nov 20 at 18:39










  • It doesn't look like your form has a clean_Email() method. That would be a good place to start.
    – John Gordon
    Nov 20 at 18:55




















  • I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
    – Robin Zigmond
    Nov 20 at 18:39










  • It doesn't look like your form has a clean_Email() method. That would be a good place to start.
    – John Gordon
    Nov 20 at 18:55


















I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
– Robin Zigmond
Nov 20 at 18:39




I'm not sure if it will do as you want, but this looks like it should really inherit from forms.ModelForm
– Robin Zigmond
Nov 20 at 18:39












It doesn't look like your form has a clean_Email() method. That would be a good place to start.
– John Gordon
Nov 20 at 18:55






It doesn't look like your form has a clean_Email() method. That would be a good place to start.
– John Gordon
Nov 20 at 18:55














2 Answers
2






active

oldest

votes


















1














If you want form validation to automatically use the model attributes, you have to use a 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.






share|improve this answer





















  • Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
    – Wessel
    Nov 21 at 9:50



















0














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>





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399300%2funique-true-in-django-model-gives-intergretyerror-instead-of-validationerror%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you want form validation to automatically use the model attributes, you have to use a 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.






    share|improve this answer





















    • Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
      – Wessel
      Nov 21 at 9:50
















    1














    If you want form validation to automatically use the model attributes, you have to use a 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.






    share|improve this answer





















    • Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
      – Wessel
      Nov 21 at 9:50














    1












    1








    1






    If you want form validation to automatically use the model attributes, you have to use a 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.






    share|improve this answer












    If you want form validation to automatically use the model attributes, you have to use a 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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 21 at 0:29









    Kevin Christopher Henry

    22.5k46361




    22.5k46361












    • Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
      – Wessel
      Nov 21 at 9:50


















    • Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
      – Wessel
      Nov 21 at 9:50
















    Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
    – Wessel
    Nov 21 at 9:50




    Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
    – Wessel
    Nov 21 at 9:50













    0














    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>





    share|improve this answer


























      0














      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>





      share|improve this answer
























        0












        0








        0






        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>





        share|improve this answer












        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>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 18:53









        Amine Messaoudi

        452414




        452414






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399300%2funique-true-in-django-model-gives-intergretyerror-instead-of-validationerror%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'