Django form with IntegrityError exception











up vote
0
down vote

favorite












I would like to get your help in order to use except IntegrityError in my formset.



I have my model file :



class Document(models.Model):

code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES)
title = models.CharField(max_length=512, verbose_name=_('title'))
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension], verbose_name=_('document file'), )

class Meta:
verbose_name = _('document')
verbose_name_plural = _('documents')

def save(self, *args, **kwargs):
self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}"
super(Document, self).save(*args, **kwargs)

def __str__(self):
return f"{self.title}"


As you can see, the code field depends from data filled by user with the associated form.
Each code field has to be unique.



I have a formset :



class DocumentForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)

for key in self.fields:
self.fields[key].required = True

class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']


DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True)


And I have a views.py file with an except IntegrityError if user fills different form in formset with same value. Because it will create the same code ang user will get an error.



class PublicationCreateView(CreateView):
model = Publication
template_name = 'publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
document_queryset = Document.objects.all()
context['DocumentFormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None,
prefix='doc', queryset=document_queryset)
return context

def form_valid(self, form):
try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return render(self.request, self.template_name)


You can find my template, but I don't know if it's necessary !



<form method="post" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{# {{ form.management_form }}#}

<fieldset>
<legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend>
<div class="row">
<div class="col-xs-6">
{{ form.category|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.pub_id|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.cover|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form.description|as_crispy_field }}
</div>
</div>
</fieldset>

<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSets.management_form }}
<div id="form_set">
{% for form in DocumentFormSets.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>

<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
<a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default">{% trans 'Cancel' %}</a>
</form>


I get this issue :



Exception Value: |as_crispy_field got passed an invalid or inexistent field


Because :




The above exception (duplicate key value violates unique constraint
"freepub_document_code_key" DETAIL: Key (code)=(PUBSD-8119-FR-PDF)
already exists. ) was the direct cause of the following exception:
formsets.save()




EDIT :



I tried :



try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return super(PublicationCreateView, self).form_invalid(form)


I seems to work, but maybe I don't have to same my first form because he has unique value too and if I change value according to form_invalid(), I have to change this one too.










share|improve this question




















  • 1




    You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
    – Alex
    Nov 22 at 15:43












  • Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
    – ChocoBomb
    Nov 26 at 14:04










  • Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
    – Alex
    Nov 26 at 14:29















up vote
0
down vote

favorite












I would like to get your help in order to use except IntegrityError in my formset.



I have my model file :



class Document(models.Model):

code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES)
title = models.CharField(max_length=512, verbose_name=_('title'))
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension], verbose_name=_('document file'), )

class Meta:
verbose_name = _('document')
verbose_name_plural = _('documents')

def save(self, *args, **kwargs):
self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}"
super(Document, self).save(*args, **kwargs)

def __str__(self):
return f"{self.title}"


As you can see, the code field depends from data filled by user with the associated form.
Each code field has to be unique.



I have a formset :



class DocumentForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)

for key in self.fields:
self.fields[key].required = True

class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']


DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True)


And I have a views.py file with an except IntegrityError if user fills different form in formset with same value. Because it will create the same code ang user will get an error.



class PublicationCreateView(CreateView):
model = Publication
template_name = 'publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
document_queryset = Document.objects.all()
context['DocumentFormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None,
prefix='doc', queryset=document_queryset)
return context

def form_valid(self, form):
try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return render(self.request, self.template_name)


You can find my template, but I don't know if it's necessary !



<form method="post" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{# {{ form.management_form }}#}

<fieldset>
<legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend>
<div class="row">
<div class="col-xs-6">
{{ form.category|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.pub_id|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.cover|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form.description|as_crispy_field }}
</div>
</div>
</fieldset>

<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSets.management_form }}
<div id="form_set">
{% for form in DocumentFormSets.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>

<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
<a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default">{% trans 'Cancel' %}</a>
</form>


I get this issue :



Exception Value: |as_crispy_field got passed an invalid or inexistent field


Because :




The above exception (duplicate key value violates unique constraint
"freepub_document_code_key" DETAIL: Key (code)=(PUBSD-8119-FR-PDF)
already exists. ) was the direct cause of the following exception:
formsets.save()




EDIT :



I tried :



try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return super(PublicationCreateView, self).form_invalid(form)


I seems to work, but maybe I don't have to same my first form because he has unique value too and if I change value according to form_invalid(), I have to change this one too.










share|improve this question




















  • 1




    You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
    – Alex
    Nov 22 at 15:43












  • Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
    – ChocoBomb
    Nov 26 at 14:04










  • Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
    – Alex
    Nov 26 at 14:29













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I would like to get your help in order to use except IntegrityError in my formset.



I have my model file :



class Document(models.Model):

code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES)
title = models.CharField(max_length=512, verbose_name=_('title'))
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension], verbose_name=_('document file'), )

class Meta:
verbose_name = _('document')
verbose_name_plural = _('documents')

def save(self, *args, **kwargs):
self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}"
super(Document, self).save(*args, **kwargs)

def __str__(self):
return f"{self.title}"


As you can see, the code field depends from data filled by user with the associated form.
Each code field has to be unique.



I have a formset :



class DocumentForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)

for key in self.fields:
self.fields[key].required = True

class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']


DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True)


And I have a views.py file with an except IntegrityError if user fills different form in formset with same value. Because it will create the same code ang user will get an error.



class PublicationCreateView(CreateView):
model = Publication
template_name = 'publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
document_queryset = Document.objects.all()
context['DocumentFormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None,
prefix='doc', queryset=document_queryset)
return context

def form_valid(self, form):
try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return render(self.request, self.template_name)


You can find my template, but I don't know if it's necessary !



<form method="post" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{# {{ form.management_form }}#}

<fieldset>
<legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend>
<div class="row">
<div class="col-xs-6">
{{ form.category|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.pub_id|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.cover|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form.description|as_crispy_field }}
</div>
</div>
</fieldset>

<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSets.management_form }}
<div id="form_set">
{% for form in DocumentFormSets.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>

<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
<a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default">{% trans 'Cancel' %}</a>
</form>


I get this issue :



Exception Value: |as_crispy_field got passed an invalid or inexistent field


Because :




The above exception (duplicate key value violates unique constraint
"freepub_document_code_key" DETAIL: Key (code)=(PUBSD-8119-FR-PDF)
already exists. ) was the direct cause of the following exception:
formsets.save()




EDIT :



I tried :



try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return super(PublicationCreateView, self).form_invalid(form)


I seems to work, but maybe I don't have to same my first form because he has unique value too and if I change value according to form_invalid(), I have to change this one too.










share|improve this question















I would like to get your help in order to use except IntegrityError in my formset.



I have my model file :



class Document(models.Model):

code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='')
language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES)
title = models.CharField(max_length=512, verbose_name=_('title'))
publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents')
upload = models.FileField(upload_to='media/', validators=[validate_file_extension], verbose_name=_('document file'), )

class Meta:
verbose_name = _('document')
verbose_name_plural = _('documents')

def save(self, *args, **kwargs):
self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}"
super(Document, self).save(*args, **kwargs)

def __str__(self):
return f"{self.title}"


As you can see, the code field depends from data filled by user with the associated form.
Each code field has to be unique.



I have a formset :



class DocumentForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(DocumentForm, self).__init__(*args, **kwargs)

for key in self.fields:
self.fields[key].required = True

class Meta:
model = Document
fields = ['publication', 'language', 'format', 'title', 'upload']


DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True)


And I have a views.py file with an except IntegrityError if user fills different form in formset with same value. Because it will create the same code ang user will get an error.



class PublicationCreateView(CreateView):
model = Publication
template_name = 'publication_form.html'

def get_context_data(self, **kwargs):
context = super(PublicationCreateView, self).get_context_data(**kwargs)
document_queryset = Document.objects.all()
context['DocumentFormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None,
prefix='doc', queryset=document_queryset)
return context

def form_valid(self, form):
try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return render(self.request, self.template_name)


You can find my template, but I don't know if it's necessary !



<form method="post" action="" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{# {{ form.management_form }}#}

<fieldset>
<legend class="title"><span class="name">{% trans 'Publication form' %}</span></legend>
<div class="row">
<div class="col-xs-6">
{{ form.category|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.pub_id|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-6">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-6">
{{ form.cover|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ form.description|as_crispy_field }}
</div>
</div>
</fieldset>

<fieldset>
<legend class="title"><span class="name">{% trans 'Document form' %}</span></legend>
{{ DocumentFormSets.management_form }}
<div id="form_set">
{% for form in DocumentFormSets.forms %}
<div class='formset-document'>
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
{% endfor %}
</div>
<br>
<input type="button" class="btn btn-default" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
<table class='no_error'>
<div class="row">
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.title|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.language|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.format|as_crispy_field }}
</div>
<div class="col-xs-3">
{{ DocumentFormSets.empty_form.upload|as_crispy_field }}
</div>
</div>
</table>
</div>
</fieldset>

<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/>
<a href="{{ request.META.HTTP_REFERER }}" class="btn btn-default">{% trans 'Cancel' %}</a>
</form>


I get this issue :



Exception Value: |as_crispy_field got passed an invalid or inexistent field


Because :




The above exception (duplicate key value violates unique constraint
"freepub_document_code_key" DETAIL: Key (code)=(PUBSD-8119-FR-PDF)
already exists. ) was the direct cause of the following exception:
formsets.save()




EDIT :



I tried :



try:
context = self.get_context_data()
formsets = context['DocumentFormSets']
if form.is_valid():
self.object = form.save()
if formsets.is_valid():
formsets.instance = self.object
formsets.save(commit=False)
for element in formsets:
element.save(commit=False)
formsets.save()
return super(PublicationCreateView, self).form_valid(form)
except IntegrityError:
messages.error(self.request, _(f"Issue with documents"))
return super(PublicationCreateView, self).form_invalid(form)


I seems to work, but maybe I don't have to same my first form because he has unique value too and if I change value according to form_invalid(), I have to change this one too.







python django exception django-crispy-forms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 14:11

























asked Nov 22 at 14:04









ChocoBomb

548




548








  • 1




    You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
    – Alex
    Nov 22 at 15:43












  • Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
    – ChocoBomb
    Nov 26 at 14:04










  • Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
    – Alex
    Nov 26 at 14:29














  • 1




    You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
    – Alex
    Nov 22 at 15:43












  • Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
    – ChocoBomb
    Nov 26 at 14:04










  • Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
    – Alex
    Nov 26 at 14:29








1




1




You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
– Alex
Nov 22 at 15:43






You shouldn't wait for it to crash on .save(). Probably worth looking into overriding clean() and trying to validate there if the code that'll be generated already exists or not.
– Alex
Nov 22 at 15:43














Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
– ChocoBomb
Nov 26 at 14:04




Ok, but how it's possible to do that ? clean() should be defined in models.py file ?
– ChocoBomb
Nov 26 at 14:04












Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
– Alex
Nov 26 at 14:29




Yes, you can define clean() method in a Model: docs.djangoproject.com/en/2.0/ref/models/instances/…
– Alex
Nov 26 at 14:29

















active

oldest

votes











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',
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%2f53432711%2fdjango-form-with-integrityerror-exception%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















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%2f53432711%2fdjango-form-with-integrityerror-exception%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

What visual should I use to simply compare current year value vs last year in Power BI desktop

How to ignore python UserWarning in pytest?

Alexandru Averescu