'django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name) already exists

I have a Custome User model defined in the models.py

class User(AbstractUser):
    is_verified = models.BooleanField(default=False)
    phone_number = models.CharField(max_length=14, null=True)
    role = models.CharField(max_length=30, choices=ROLE_TYPE, default=ROLE_TYPE[0][0])
    district = models.ForeignKey(District, on_delete=models.CASCADE, null=True)
    facility = models.ForeignKey(Facility, on_delete=models.CASCADE, null=True)

    REQUIRED_FIELDS = ["email", "first_name"]

I have already set the customer user model in the app. Now I'm trying to create some groups and assign them some permission based on the group.

admin_user = Group(name='special_user')
admin_user.save()

user_ct = ContentType.objects.get(app_label='users', model=User)
can_create = Permission(name='Can create user', content_type=user_ct, codename='can_create_users')
can_create.save()

admin_user.permissions.add(can_create)

But now I'm getting the following error:-

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "auth_group_name_key"
DETAIL:  Key (name)=(Special users) already exists.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\apps\config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\gdc\GDC-Level-10-Milestone-master\arike\arike\users\models.py", line 40, in <module>
    admin_user.save()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 739, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 776, in save_base
    updated = self._save_table(
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 881, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 919, in _do_insert
    return manager._insert(
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
    with self.db.wrap_database_errors:
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_group_name_key"
DETAIL:  Key (name)=(Special users) already exists.

(env) 
Rahul Tiwari@localhostAnkur MINGW64 ~/Desktop/My_Projects/gdc/GDC-Level-10-Milestone-master/arike (main)
$ python manage.py runserver
Watching for file changes with StatReloader
INFO 2022-03-04 11:57:41,830 autoreload 14660 13080 Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "auth_group_name_key"
DETAIL:  Key (name)=(special_user) already exists.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\apps\config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\gdc\GDC-Level-10-Milestone-master\arike\arike\users\models.py", line 40, in <module>
    admin_user.save()
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 739, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 776, in save_base
    updated = self._save_table(
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 881, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 919, in _do_insert
    return manager._insert(
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
    with self.db.wrap_database_errors:
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_group_name_key"
DETAIL:  Key (name)=(special_user) already exists.

I've tried using the different values in the name field in Group but every time it shows the same error. I don't know where I'm doing wrong. Someone help me for figuring out the solution.



Solution 1:[1]

You each time try to create a new group with the name special_user, you can work with .get_or_create(…) [Django-doc] to create the group only if it does not yet exists in the database:

admin_user, __ = Group.objects.get_or_create(name='special_user')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem