La adición de nuevos permisos personalizados en Django
-
20-09-2019 - |
Pregunta
Estoy utilizando permisos personalizados en mis modelos de Django como esto:
class T21Turma(models.Model):
class Meta:
permissions = (("can_view_boletim", "Can view boletim"),
("can_view_mensalidades", "Can view mensalidades"),)
El problema es que cuando agrego un permiso de la lista que no consigue agrega a la tabla auth_permission
cuando corro syncdb. Qué estoy haciendo mal. Si hace alguna diferencia que estoy usando al sur para las migraciones de bases de datos.
Solución
Sur no hace un seguimiento django.contrib.auth permisos. Ver boleto # 211 para más información.
Uno de los comentarios sobre el billete sugiere que el uso de la opción --all
en syncdb puede resolver el problema.
Otros consejos
Si desea "manage.py migrar" a hacer todo lo posible (sin llamar --all syncdb). Es necesario crear nuevos permisos con una migración:
user@host> manage.py datamigration myapp add_perm_foo --freeze=contenttypes --freeze=auth
Editar el archivo creado:
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
ct, created = orm['contenttypes.ContentType'].objects.get_or_create(
model='mymodel', app_label='myapp') # model must be lowercase!
perm, created = orm['auth.permission'].objects.get_or_create(
content_type=ct, codename='mymodel_foo', defaults=dict(name=u'Verbose Name'))
Esto funcionó para mí:
./manage.py update_permissions
Es un href="https://github.com/django-extensions/django-extensions"> django-extensiones cosa
Puede conectarse a la señal post_migrate
con el fin de actualizar los permisos después de la migración. Utilizo el siguiente código, ligeramente modificado a partir de Dev con Passion y originalmente de django-extensiones .
# Add to your project-level __init__.py
from south.signals import post_migrate
def update_permissions_after_migration(app,**kwargs):
"""
Update app permission just after every migration.
This is based on app django_extensions update_permissions management command.
"""
from django.conf import settings
from django.db.models import get_app, get_models
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
post_migrate.connect(update_permissions_after_migration)
Cuando i runnning migración con siguiente código
ct, created = orm['contenttypes.ContentType'].objects.get_or_create(model='mymodel', app_label='myapp') # model must bei lowercase!
perm, created = orm['auth.permission'].objects.get_or_create(content_type=ct, codename='mymodel_foo')
Me conseguir siguiente error
File "C:\Python26\lib\site-packages\south-0.7.3-py2.6.egg\south\orm.py", line 170, in __getitem__
raise KeyError("The model '%s' from the app '%s' is not available in this migration." % (model, app))
KeyError: "The model 'contenttype' from the app 'contenttypes' is not available in this migration."
Para evitar este error, he modificado el código
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
ct = ContentType.objects.get(model='mymodel', app_label='myapp')
perm, created = Permission.objects.get_or_create(content_type=ct, codename='mymodel_foo')
if created:
perm.name=u'my permission description'
perm.save()