Django Permission

196 views
Skip to first unread message

Aadil Rashid

unread,
Oct 5, 2021, 11:38:14 PM10/5/21
to Django users
I am creating custom permission in my Django myapp's module with the follwing code;

from myapp.models import BlogPost
from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType 

content_type = ContentType.objects.get_for_model(BlogPost) 

permission = Permission.objects.create(
codename='can_publish', 
  name='Can Publish Posts', 
  content_type=content_type, )

when i use this permission in my views, i get the following error,

File "/home/aadil/.local/share/virtualenvs/crawling_next-ao7NwWLu/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute

return Database.Cursor.execute(self, query, params)

django.db.utils.IntegrityError: UNIQUE constraint failed: auth_permission.content_type_id, auth_permission.codename

I am new to djagno please help??

Steven Mapes

unread,
Oct 6, 2021, 9:22:23 AM10/6/21
to Django users
If you have the code in a file as you have then what's happening is that you trying to create the same Permission everytime Django runs.  What you want to do is to create the permission against the BlogPost model itself within the class Meta. Then run a makemigrations and migrate to create the permission once. After that you'll be able to use it.

Reply all
Reply to author
Forward
0 new messages