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.
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
add a comment |
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
I'm not sure if it will do as you want, but this looks like it should really inherit fromforms.ModelForm
– Robin Zigmond
Nov 20 at 18:39
It doesn't look like your form has aclean_Email()
method. That would be a good place to start.
– John Gordon
Nov 20 at 18:55
add a comment |
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
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
python django sqlite3
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 fromforms.ModelForm
– Robin Zigmond
Nov 20 at 18:39
It doesn't look like your form has aclean_Email()
method. That would be a good place to start.
– John Gordon
Nov 20 at 18:55
add a comment |
I'm not sure if it will do as you want, but this looks like it should really inherit fromforms.ModelForm
– Robin Zigmond
Nov 20 at 18:39
It doesn't look like your form has aclean_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
add a comment |
2 Answers
2
active
oldest
votes
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.
Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
– Wessel
Nov 21 at 9:50
add a comment |
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>
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
– Wessel
Nov 21 at 9:50
add a comment |
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.
Thanks a lot!! This is exactly wat I was looking for. Works like a charm!
– Wessel
Nov 21 at 9:50
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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>
add a comment |
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>
add a comment |
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>
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>
answered Nov 20 at 18:53
Amine Messaoudi
452414
452414
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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