Cause of Django duplicate entry error (1062)? - django

I updated the info below to reference a different model/view that is giving me the same error. Its a simpler model so there are less variables to take into account...
I have the following model:
class Imaging_order(Order):
order_description = models.ForeignKey(Imaging_test, limit_choices_to = {'active': 1}, null=True, blank=True)
orders = models.ManyToManyField(Imaging_test, limit_choices_to = {'active': 1}, related_name='orders')
...
I have the following views (basically the generic django class based update view with a couple custom functions mixed in):
class LoginRequiredMixin(object):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class EditMixin(object):
def form_valid(self, form):
messages.success(self.request, "This %s has been updated." % (self.model._meta.verbose_name), extra_tags='msg')
return super(EditMixin, self).form_valid(form)
class ImagingMixin(LoginRequiredMixin):
model = Imaging_order
form_class = ImagingForm
class ImagingUpdateView(ImagingMixin, EditMixin, UpdateView):
pass
On our live version I occassionally get notices of this error:
Traceback (most recent call last):
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/views/generic/base.py", line 47, in view
return self.dispatch(request, *args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/utils/decorators.py", line 28, in _wrapper
return bound_func(*args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/utils/decorators.py", line 24, in bound_func
return func(self, *args2, **kwargs2)
File "/home/cpcadmin/webapps/cpcdj2/cpc/emr/views.py", line 150, in dispatch
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/views/generic/base.py", line 68, in dispatch
return handler(request, *args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/views/generic/edit.py", line 195, in post
return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/views/generic/edit.py", line 138, in post
return self.form_valid(form)
File "/home/cpcadmin/webapps/cpcdj2/cpc/emr/views.py", line 155, in form_valid
return super(EditMixin, self).form_valid(form)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/views/generic/edit.py", line 112, in form_valid
self.object = form.save()
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/forms/models.py", line 363, in save
fail_message, commit, construct=False)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/forms/models.py", line 86, in save_instance
save_m2m()
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/forms/models.py", line 82, in save_m2m
f.save_form_data(instance, cleaned_data[f.name])
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/fields/related.py", line 1149, in save_form_data
setattr(instance, self.attname, data)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/fields/related.py", line 746, in __set__
manager.add(*value)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/fields/related.py", line 503, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/fields/related.py", line 587, in _add_items
'%s_id' % target_field_name: obj_id,
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/query.py", line 360, in create
obj.save(force_insert=True, using=self.db)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/base.py", line 553, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/query.py", line 1436, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/sql/compiler.py", line 791, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/home/cpcadmin/webapps/cpcdj2/lib/python2.7/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '25129-18' for key 2")
I cannot tell when this error is occurring (usually this view works just fine). I think I have a normal model/view/form setup except that I extended the generic class-based views a bit. I agree with the below comment that this is related to a m2m field. Every time this error comes up it is calling "save_m2m", which then results in this error. I still can't reproduce it. It occurs from my update page/view so I think its only when updating an existing model with existing related records. This is the closest other post I could find, but was of no help: IntegrityError: (1062, "Duplicate entry '1830327-1792993' for key 'some_instance_A_id'") but no UNIQUE constraint

Related

django - overriding save method with super returns unique contraint error when creating object

Overriding save method with super returns unique contraint error when creating object. How to solve it?
Adding context to the code. I need to create an object1 and I need to assign some value dependent on a related foreign object. I need to assign the value after creating an instance of object1, otherwise an error pops up that the object does not exist and there is no relationship.
def save(self, *args, **kwargs):
if self.pk is None:
super(IntoDocumentProduct, self).save(*args, **kwargs)
# some logic
# more logic
super(IntoDocumentProduct, self).save(*args, **kwargs)
self.full_clean()
I am also posting the error that shows up when I test the api in insomnia.
IntegrityError at /api/wms/intodocuments/products/create/
duplicate key value violates unique constraint "wms_dokumentprzyjeciaprodukt_pkey"
DETAIL: Key (id)=(151) already exists.
Below is the error that appears in the console. It directs specifically to the save() method in the model. I don't know what is wrong with it. After all, I can't use self.save(), because there will be a recursive loop.
Traceback (most recent call last):
File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 81, in inner
return func(*args, **kwds)
^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\src\wms\api\views.py", line 183, in post
serializer.save()
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\query.py", line 671, in create
obj.save(force_insert=True, using=self.db)
File "W:\projects\foodgast\src\wms\models.py", line 621, in save
super(IntoDocumentProduct, self).save(*args, **kwargs)
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\base.py", line 812, in save
self.save_base(
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\base.py", line 863, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\base.py", line 1006, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\base.py", line 1047, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\query.py", line 1791, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\models\sql\compiler.py", line 1660, in execute_sql
cursor.execute(sql, params)
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\backends\utils.py", line 103, in execute
return super().execute(sql, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "W:\projects\foodgast\venv\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
django.db.utils.IntegrityError: duplicate key value violates unique constraint "wms_dokumentprzyjeciaprodukt_pkey"
DETAIL: Key (id)=(150) already exists.
I'm like 90% sure you have to define your super properly. I tried what you have and didn't get a compile error, but it's definitely not best practices. Particularly, if you're not defining a return within your if statement. That would cause super to be called twice which could be throwing the exception due to the save function running twice. I typically set it right after my function declaration (my prefered method) or as my last line.
def save(self, *args, **kwargs):
super(IntoDocumentProduct, self).save(*args, **kwargs)
# your overwrite code
or
def save(self, *args, **kwargs):
# your overwrite code
super(IntoDocumentProduct, self).save(*args, **kwargs)

How to save django manytomany field without through table

I face a vicious cycle that I cannot break out of;
Lets say I have a following model:
class AgregatorProductCoupon(models.Model):
AgregatorProductId = models.ManyToManyField(Product, related_name="coupons", db_column='AgregatorProductId', verbose_name=_("Agregator Product Id"))
class Meta:
managed = True
db_table = 'AgregatorProductCoupon'
when I try to save an instance, I get an integrity error stating
"<AgregatorProductCoupon: AgregatorProductCoupon object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
but when I try to save without the m2m rel, I obviously get an error for a required field missing.
Cannot insert the value NULL into column 'AgregatorProductId', table 'test_dbo.dbo.AgregatorProductCoupon'; column does not allow nulls. INSERT fails.
I cannot redesign the tables as they are bound to other places too.
How to go about it?
Any help would be much appreciated.
EDIT: Traceback:
[2021-01-07 13:19:28,040] log_response - Internal Server Error: /admin/agregator/agregatorcoupons/78/change/
Traceback (most recent call last):
File "C:\David\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\David\.venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\David\.venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 1650, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\David\.venv\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 1536, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 1576, in _changeform_view
self.save_related(request, form, formsets, not add)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 1122, in save_related
self.save_formset(request, form, formset, change=change)
File "C:\David\.venv\lib\site-packages\django\contrib\admin\options.py", line 1110, in save_formset
formset.save()
File "C:\David\.venv\lib\site-packages\django\forms\models.py", line 669, in save
return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "C:\David\.venv\lib\site-packages\django\forms\models.py", line 803, in save_new_objects
self.new_objects.append(self.save_new(form, commit=commit))
File "C:\David\.venv\lib\site-packages\django\forms\models.py", line 949, in save_new
obj.save()
File "C:\David\agregator\models.py", line 2745, in save
print(self.AgregatorProductId)
File "C:\David\.venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 526, in __get__
return self.related_manager_cls(instance)
File "C:\David\.venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 821, in __init__
raise ValueError('"%r" needs to have a value for field "%s" before '
ValueError: "<AgregatorProductCoupon: AgregatorProductCoupon object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.

Integrity Error django with UniqueConstraint

I have the following model snippet:
class InvoiceReference(TemplateMixin, models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
reference_prefix = models.CharField(
max_length=100,
validators=(RegexValidator(regex='^\S+$',
message='reference prefix must not include spaces'),)
)
reference_offset = models.PositiveIntegerField(default=0)
reference_suffix = models.CharField(
max_length=100,
validators=(RegexValidator(regex='^\S+$',
message='reference suffix must not include spaces'),)
)
reference_separator = models.CharField(max_length=1)
class Meta:
constraints = [
models.UniqueConstraint(fields=('user', 'reference_prefix', 'reference_suffix', 'reference_separator',), name='unique_reference')
]
The idea is to have it so that a no single user cannot use the same reference_prefix, reference_separator and reference_suffix together multiple times. (if different users use the same combination of reference_prefix, reference_separator and reference_suffix this is ok.)
I am currently using the django-admin model form, where I have excluded the user field and attach a user in save_model:
class InvoiceReferenceAdmin(admin.ModelAdmin):
model = InvoiceReference
exclude = ('user',)
def save_model(self, request, obj, form, change):
if not obj.pk:
obj.user = request.user
super().save_model(request=request, obj=obj, form=form, change=change)
however, this results in an 'Integrity Error' when I try to save the model.
Traceback:
Traceback (most recent call last):
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: invoice_invoice.user_id, invoice_invoice.reference_prefix, invoice_invoice.reference_suffix, invoice_invoice.reference_separator
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "django/contrib/admin/options.py", line 1645, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "django/contrib/admin/options.py", line 1529, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "django/contrib/admin/options.py", line 1572, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/Users/leonhughes/dev/django/invoiceweb/invoice/admin.py", line 42, in save_model
super().save_model(request=request, obj=obj, form=form, change=change)
File "django/contrib/admin/options.py", line 1088, in save_model
obj.save()
File "django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "django/db/models/sql/compiler.py", line 1375, in execute_sql
cursor.execute(sql, params)
File "django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: invoice_invoice.user_id, invoice_invoice.reference_prefix, invoice_invoice.reference_suffix, invoice_invoice.reference_separator
I have seen this in the django documentation
In general constraints are not checked during full_clean(), and do not
raise ValidationErrors. Rather you’ll get a database integrity error
on save(). UniqueConstraints without a condition (i.e. non-partial
unique constraints) are different in this regard, in that they
leverage the existing validate_unique() logic, and thus enable
two-stage validation. In addition to IntegrityError on save(),
ValidationError is also raised during model validation when the
UniqueConstraint is violated.
As I have no conditions set shouldn't a ValidationError be raised first?
One way to achieve a similar result as yours would be to make user a hidden field in your admin form and then override ModelAdmin.get_changeform_initial_data to pass the current user as the value for this hidden input.
This would mean that the user would be included in unique validation checks as the field would not be excluded from the form. When editing an existing object initial data is ignored so you shouldn't override any existing user relation
class InvoiceReferenceAdminForm(forms.ModelForm):
class Meta:
model = InvoiceReference
fields = '__all__'
widgets = {'user': forms.HiddenInput}
class InvoiceReferenceAdmin(admin.ModelAdmin):
model = InvoiceReference
form = InvoiceReferenceAdminForm
def get_changeform_initial_data(self, request):
return {'user': request.user}

Generate unique string for each db object

I have a model where I need to create a UNIQUE string for each object in the db.
I've made a function to generate the string, but I can create an object using the django admin once, and then the second time it will error out and say that the value is not unique.
What can I do so Django just generates a new string if the previous one was used already?
models.py
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
class Refferal(models.Model):
email = models.EmailField(max_length=254, unique=True)
coupon = models.CharField(default=randomword(4), primary_key=True, editable=False, max_length=4)
count = models.IntegerField(default=0)
Log output from when I try to create the second object using the admin
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1638, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1565, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1081, in save_model
obj.save()
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert
using=using, raw=raw,
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1384, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "index_refferal_coupon_a6e4bc31_pk"
DETAIL: Key (coupon)=(vtgs) already exists.
You here will evaluate eagerly the call randomword(4), and set the result of that function call as default value. You can however pass a callable:
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
def random4():
return randomword(4)
class Refferal(models.Model):
email = models.EmailField(max_length=254, unique=True)
coupon = models.CharField(default=random4, primary_key=True, editable=False, max_length=4)
count = models.IntegerField(default=0)
Note that we do not call the function. We only pass a reference to the function.
That being said, it might be better to use Django's UUIDField [Django-doc]. This is made to store and generate random UUIDs, which are likely better sources of random strings.

django-allauth - Using custom adapter gives error: UNIQUE constraint failed: main_user.email

My custom adapters.py file contains this (and I've linked to it in settings.py correctly, of course):
from allauth.account.adapter import DefaultAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=True):
data = form.cleaned_data
user.username = data.get('username')
user.email = data.get('email')
user.first_name = data.get('first_name')
user.last_name = data.get('last_name')
user.gender = data.get('gender')
user.birth_date = data.get('birth_date')
user.city = data.get('city')
user.country = data.get('country')
if 'password1' in data:
user.set_password(data.get('password1'))
else:
user.set_unusable_password()
self.populate_username(request, user)
if commit:
user.save()
return user
The error happens somewhere in the code in allauth, and I can't figure out why. I've did the same like in original adapter save method, but for some reason it doesn't work for my custom one.
Here's a full stack trace if someone wants to see that, too:
Traceback (most recent call last):
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/views.py", line 177, in dispatch
return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/views.py", line 66, in dispatch
**kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/views.py", line 155, in dispatch
**kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/views.py", line 82, in post
response = self.form_valid(form)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/views.py", line 192, in form_valid
self.user = form.save(self.request)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/forms.py", line 316, in save
self.custom_signup(request, user)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/allauth/account/forms.py", line 285, in custom_signup
custom_form.save(user)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/contrib/auth/forms.py", line 99, in save
user.save()
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 74, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/base.py", line 859, in _do_insert
using=using, raw=raw)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mikisoft/django-dev/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: main_user.email
I've fixed it, the problem was with my signup form (in forms.py). It now looks like this:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.forms import extras
from django.contrib.auth import get_user_model
BIRTH_DATE_YEARS = ('2015','2014','2013','2012','2011','2010','2009','2008','2007','2006','2005','2004','2003','2002',
'2001','2000','1999','1998','1997','1996','1995','1994','1993','1992','1991','1990','1989','1988',
'1987','1986','1985','1984','1983','1982','1981','1980','1979','1978','1977','1976','1975','1974',
'1973','1972','1971','1970','1969','1968','1967','1966','1965','1964','1963','1962','1961','1960',
'1959','1958','1957','1956','1955','1954','1953','1952','1951','1950','1949','1948','1947','1946',
'1945','1944','1943','1942','1941','1940','1939','1938','1937','1936','1935','1934','1933','1932',
'1931','1930','1929','1928','1927')
class RegistrationForm(UserCreationForm):
birth_date = forms.DateField(widget=extras.SelectDateWidget(years=BIRTH_DATE_YEARS))
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'gender', 'birth_date', 'city', 'country')
def signup(self, request, user):
pass