Add from __future__ import unicode_literals, issue #37

This commit is contained in:
Roberto Rosario
2015-01-19 04:06:40 -04:00
parent efbac7300c
commit d59ea3ede2
334 changed files with 2452 additions and 2268 deletions

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
__title__ = 'Mayan EDMS'
__version__ = '1.1.0'
__build__ = 0x010100

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.dispatch import receiver

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin
@@ -6,12 +6,11 @@ from .models import AccessEntry
class AccessEntryAdmin(admin.ModelAdmin):
model = AccessEntry
list_display = ('pk', 'holder_object', 'permission', 'content_object')
list_display_links = ('pk',)
related_lookup_fields = {
'generic': [['holder_type', 'holder_id'], ['content_type', 'object_id']],
}
# inlines = [PermissionHolderInline]
list_display = ('pk', 'holder_object', 'permission', 'content_object')
list_display_links = ('pk',)
model = AccessEntry
admin.site.register(AccessEntry, AccessEntryAdmin)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType

View File

@@ -23,7 +23,7 @@ def get_source_object(obj):
class EncapsulatedObject(object):
source_object_name = u'source_object'
source_object_name = 'source_object'
@classmethod
def object_key(cls, app_label=None, model=None, pk=None):
@@ -82,14 +82,14 @@ class EncapsulatedObject(object):
try:
content_type = ContentType.objects.get(app_label=app_label, model=model)
except ContentType.DoesNotExist:
raise ObjectDoesNotExist("%s matching query does not exist." % ContentType._meta.object_name)
raise ObjectDoesNotExist('%s matching query does not exist.' % ContentType._meta.object_name)
else:
source_object_model_class = content_type.model_class()
if pk:
try:
source_object = content_type.get_object_for_this_type(pk=pk)
except source_object_model_class.DoesNotExist:
raise ObjectDoesNotExist("%s matching query does not exist." % source_object_model_class._meta.object_name)
raise ObjectDoesNotExist('%s matching query does not exist.' % source_object_model_class._meta.object_name)
else:
source_object = source_object_model_class
@@ -112,13 +112,13 @@ class EncapsulatedObject(object):
if isinstance(self.source_object, ModelBase):
return unicode(self.source_object._meta.verbose_name_plural)
elif self.ct_fullname == 'auth.user':
return u'%s %s' % (self.source_object._meta.verbose_name, self.source_object.get_full_name())
return '%s %s' % (self.source_object._meta.verbose_name, self.source_object.get_full_name())
elif self.ct_fullname == 'common.anonymoususersingleton':
return unicode(self.source_object)
elif self.ct_fullname == 'acls.creatorsingleton':
return unicode(self.source_object)
else:
return u'%s %s' % (self.source_object._meta.verbose_name, self.source_object)
return '%s %s' % (self.source_object._meta.verbose_name, self.source_object)
def __repr__(self):
return self.__unicode__()
@@ -129,19 +129,19 @@ class EncapsulatedObject(object):
class AccessHolder(EncapsulatedObject):
source_object_name = u'holder_object'
source_object_name = 'holder_object'
class AccessObject(EncapsulatedObject):
source_object_name = u'obj'
source_object_name = 'obj'
class AccessObjectClass(EncapsulatedObject):
source_object_name = u'cls'
source_object_name = 'cls'
class ClassAccessHolder(EncapsulatedObject):
source_object_name = u'class_holder'
source_object_name = 'class_holder'
if sys.version_info < (2, 5):

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib.auth.models import User, Group
@@ -22,7 +22,7 @@ def _as_choice_list(holders):
class BaseHolderSelectionForm(forms.Form):
holder_gid = forms.ChoiceField(
label=_(u'New holder')
label=_('New holder')
)
def __init__(self, *args, **kwargs):
@@ -39,16 +39,16 @@ class BaseHolderSelectionForm(forms.Form):
non_holder_list = []
if users:
non_holder_list.append((_(u'Users'), _as_choice_list(list(users))))
non_holder_list.append((_('Users'), _as_choice_list(list(users))))
if groups:
non_holder_list.append((_(u'Groups'), _as_choice_list(list(groups))))
non_holder_list.append((_('Groups'), _as_choice_list(list(groups))))
if roles:
non_holder_list.append((_(u'Roles'), _as_choice_list(list(roles))))
non_holder_list.append((_('Roles'), _as_choice_list(list(roles))))
if special:
non_holder_list.append((_(u'Special'), _as_choice_list(list(special))))
non_holder_list.append((_('Special'), _as_choice_list(list(special))))
super(BaseHolderSelectionForm, self).__init__(*args, **kwargs)
self.fields['holder_gid'].choices = non_holder_list

View File

@@ -1,18 +1,20 @@
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from .permissions import (ACLS_CLASS_EDIT_ACL, ACLS_CLASS_VIEW_ACL,
ACLS_EDIT_ACL, ACLS_VIEW_ACL)
acl_list = {'text': _(u'ACLs'), 'view': 'acls:acl_list', 'famfam': 'lock', 'permissions': [ACLS_VIEW_ACL]}
acl_detail = {'text': _(u'Details'), 'view': 'acls:acl_detail', 'args': ['access_object.gid', 'object.gid'], 'famfam': 'key_go', 'permissions': [ACLS_VIEW_ACL]}
acl_grant = {'text': _(u'Grant'), 'view': 'acls:acl_multiple_grant', 'famfam': 'key_add', 'permissions': [ACLS_EDIT_ACL]}
acl_revoke = {'text': _(u'Revoke'), 'view': 'acls:acl_multiple_revoke', 'famfam': 'key_delete', 'permissions': [ACLS_EDIT_ACL]}
acl_holder_new = {'text': _(u'New holder'), 'view': 'acls:acl_holder_new', 'args': 'access_object.gid', 'famfam': 'user', 'permissions': [ACLS_EDIT_ACL]}
acl_list = {'text': _('ACLs'), 'view': 'acls:acl_list', 'famfam': 'lock', 'permissions': [ACLS_VIEW_ACL]}
acl_detail = {'text': _('Details'), 'view': 'acls:acl_detail', 'args': ['access_object.gid', 'object.gid'], 'famfam': 'key_go', 'permissions': [ACLS_VIEW_ACL]}
acl_grant = {'text': _('Grant'), 'view': 'acls:acl_multiple_grant', 'famfam': 'key_add', 'permissions': [ACLS_EDIT_ACL]}
acl_revoke = {'text': _('Revoke'), 'view': 'acls:acl_multiple_revoke', 'famfam': 'key_delete', 'permissions': [ACLS_EDIT_ACL]}
acl_holder_new = {'text': _('New holder'), 'view': 'acls:acl_holder_new', 'args': 'access_object.gid', 'famfam': 'user', 'permissions': [ACLS_EDIT_ACL]}
acl_setup_valid_classes = {'text': _(u'Default ACLs'), 'view': 'acls:acl_setup_valid_classes', 'icon': 'lock.png', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_list = {'text': _(u'Classes'), 'view': 'acls:acl_setup_valid_classes', 'famfam': 'package', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_acl_list = {'text': _(u'ACLs for class'), 'view': 'acls:acl_class_acl_list', 'args': 'object.gid', 'famfam': 'lock_go', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_acl_detail = {'text': _(u'Details'), 'view': 'acls:acl_class_acl_detail', 'args': ['access_object_class.gid', 'object.gid'], 'famfam': 'key_go', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_new_holder_for = {'text': _(u'New holder'), 'view': 'acls:acl_class_new_holder_for', 'args': 'object.gid', 'famfam': 'user', 'permissions': [ACLS_CLASS_EDIT_ACL]}
acl_class_grant = {'text': _(u'Grant'), 'view': 'acls:acl_class_multiple_grant', 'famfam': 'key_add', 'permissions': [ACLS_CLASS_EDIT_ACL]}
acl_class_revoke = {'text': _(u'Revoke'), 'view': 'acls:acl_class_multiple_revoke', 'famfam': 'key_delete', 'permissions': [ACLS_CLASS_EDIT_ACL]}
acl_setup_valid_classes = {'text': _('Default ACLs'), 'view': 'acls:acl_setup_valid_classes', 'icon': 'lock.png', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_list = {'text': _('Classes'), 'view': 'acls:acl_setup_valid_classes', 'famfam': 'package', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_acl_list = {'text': _('ACLs for class'), 'view': 'acls:acl_class_acl_list', 'args': 'object.gid', 'famfam': 'lock_go', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_acl_detail = {'text': _('Details'), 'view': 'acls:acl_class_acl_detail', 'args': ['access_object_class.gid', 'object.gid'], 'famfam': 'key_go', 'permissions': [ACLS_CLASS_VIEW_ACL]}
acl_class_new_holder_for = {'text': _('New holder'), 'view': 'acls:acl_class_new_holder_for', 'args': 'object.gid', 'famfam': 'user', 'permissions': [ACLS_CLASS_EDIT_ACL]}
acl_class_grant = {'text': _('Grant'), 'view': 'acls:acl_class_multiple_grant', 'famfam': 'key_add', 'permissions': [ACLS_CLASS_EDIT_ACL]}
acl_class_revoke = {'text': _('Revoke'), 'view': 'acls:acl_class_multiple_revoke', 'famfam': 'key_delete', 'permissions': [ACLS_CLASS_EDIT_ACL]}

View File

@@ -1,3 +1,4 @@
from __future__ import unicode_literals
# Content type <-> fam fam icon mapping
CONTENT_TYPE_ICON_MAP = {

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
@@ -115,7 +115,7 @@ class AccessEntryManager(models.Manager):
if self.has_access(permission, actor, obj):
return True
else:
raise PermissionDenied(ugettext(u'Insufficient access.'))
raise PermissionDenied(ugettext('Insufficient access.'))
def check_accesses(self, permission_list, actor, obj):
"""
@@ -127,7 +127,7 @@ class AccessEntryManager(models.Manager):
if self.has_access(permission, actor, obj):
return True
raise PermissionDenied(ugettext(u'Insufficient access.'))
raise PermissionDenied(ugettext('Insufficient access.'))
def get_allowed_class_objects(self, permission, actor, cls, related=None):
logger.debug('related: %s', related)

View File

@@ -1,20 +1,19 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext
from solo.models import SingletonModel
from permissions.models import StoredPermission
from .managers import AccessEntryManager, DefaultAccessEntryManager
from .classes import AccessObjectClass
from .api import get_classes
from .classes import AccessObjectClass
from .managers import AccessEntryManager, DefaultAccessEntryManager
logger = logging.getLogger(__name__)
@@ -23,7 +22,7 @@ class AccessEntry(models.Model):
"""
Model that hold the permission, object, actor relationship
"""
permission = models.ForeignKey(StoredPermission, verbose_name=_(u'Permission'))
permission = models.ForeignKey(StoredPermission, verbose_name=_('Permission'))
holder_type = models.ForeignKey(
ContentType,
@@ -49,11 +48,11 @@ class AccessEntry(models.Model):
objects = AccessEntryManager()
class Meta:
verbose_name = _(u'Access entry')
verbose_name_plural = _(u'Access entries')
verbose_name = _('Access entry')
verbose_name_plural = _('Access entries')
def __unicode__(self):
return u'%s: %s' % (self.content_type, self.content_object)
return '%s: %s' % (self.content_type, self.content_object)
class DefaultAccessEntry(models.Model):
@@ -65,7 +64,7 @@ class DefaultAccessEntry(models.Model):
def get_classes(cls):
return [AccessObjectClass.encapsulate(cls) for cls in get_classes()]
permission = models.ForeignKey(StoredPermission, verbose_name=_(u'Permission'))
permission = models.ForeignKey(StoredPermission, verbose_name=_('Permission'))
holder_type = models.ForeignKey(
ContentType,
@@ -86,11 +85,11 @@ class DefaultAccessEntry(models.Model):
objects = DefaultAccessEntryManager()
class Meta:
verbose_name = _(u'Default access entry')
verbose_name_plural = _(u'Default access entries')
verbose_name = _('Default access entry')
verbose_name_plural = _('Default access entries')
def __unicode__(self):
return u'%s: %s' % (self.content_type, self.content_object)
return '%s: %s' % (self.content_type, self.content_object)
class CreatorSingletonManager(models.Manager):
@@ -109,5 +108,5 @@ class CreatorSingleton(SingletonModel):
return ugettext('Creator')
class Meta:
verbose_name = _(u'Creator')
verbose_name_plural = _(u'Creator')
verbose_name = _('Creator')
verbose_name_plural = _('Creator')

View File

@@ -1,14 +1,14 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
acls_namespace = PermissionNamespace('acls', _(u'Access control lists'))
acls_setup_namespace = PermissionNamespace('acls_setup', _(u'Access control lists'))
acls_namespace = PermissionNamespace('acls', _('Access control lists'))
acls_setup_namespace = PermissionNamespace('acls_setup', _('Access control lists'))
ACLS_EDIT_ACL = Permission.objects.register(acls_namespace, 'acl_edit', _(u'Edit ACLs'))
ACLS_VIEW_ACL = Permission.objects.register(acls_namespace, 'acl_view', _(u'View ACLs'))
ACLS_EDIT_ACL = Permission.objects.register(acls_namespace, 'acl_edit', _('Edit ACLs'))
ACLS_VIEW_ACL = Permission.objects.register(acls_namespace, 'acl_view', _('View ACLs'))
ACLS_CLASS_EDIT_ACL = Permission.objects.register(acls_setup_namespace, 'acl_class_edit', _(u'Edit class default ACLs'))
ACLS_CLASS_VIEW_ACL = Permission.objects.register(acls_setup_namespace, 'acl_class_view', _(u'View class default ACLs'))
ACLS_CLASS_EDIT_ACL = Permission.objects.register(acls_setup_namespace, 'acl_class_edit', _('Edit class default ACLs'))
ACLS_CLASS_VIEW_ACL = Permission.objects.register(acls_setup_namespace, 'acl_class_view', _('View class default ACLs'))

View File

@@ -11,8 +11,8 @@ class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'AccessEntry'
db.create_table(u'acls_accessentry', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
db.create_table('acls_accessentry', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('permission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['permissions.StoredPermission'])),
('holder_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='access_holder', to=orm['contenttypes.ContentType'])),
('holder_id', self.gf('django.db.models.fields.PositiveIntegerField')()),
@@ -22,8 +22,8 @@ class Migration(SchemaMigration):
db.send_create_signal(u'acls', ['AccessEntry'])
# Adding model 'DefaultAccessEntry'
db.create_table(u'acls_defaultaccessentry', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
db.create_table('acls_defaultaccessentry', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('permission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['permissions.StoredPermission'])),
('holder_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='default_access_entry_holder', to=orm['contenttypes.ContentType'])),
('holder_id', self.gf('django.db.models.fields.PositiveIntegerField')()),
@@ -32,55 +32,55 @@ class Migration(SchemaMigration):
db.send_create_signal(u'acls', ['DefaultAccessEntry'])
# Adding model 'CreatorSingleton'
db.create_table(u'acls_creatorsingleton', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
db.create_table('acls_creatorsingleton', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('lock_id', self.gf('django.db.models.fields.CharField')(default='1', unique=True, max_length=1)),
))
db.send_create_signal(u'acls', ['CreatorSingleton'])
db.send_create_signal('acls', ['CreatorSingleton'])
def backwards(self, orm):
# Deleting model 'AccessEntry'
db.delete_table(u'acls_accessentry')
db.delete_table('acls_accessentry')
# Deleting model 'DefaultAccessEntry'
db.delete_table(u'acls_defaultaccessentry')
db.delete_table('acls_defaultaccessentry')
# Deleting model 'CreatorSingleton'
db.delete_table(u'acls_creatorsingleton')
db.delete_table('acls_creatorsingleton')
models = {
u'acls.accessentry': {
'acls.accessentry': {
'Meta': {'object_name': 'AccessEntry'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'object_content_type'", 'to': u"orm['contenttypes.ContentType']"}),
'holder_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'holder_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'access_holder'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['permissions.StoredPermission']"})
},
u'acls.creatorsingleton': {
'acls.creatorsingleton': {
'Meta': {'object_name': 'CreatorSingleton'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lock_id': ('django.db.models.fields.CharField', [], {'default': "'1'", 'unique': 'True', 'max_length': '1'})
},
u'acls.defaultaccessentry': {
'acls.defaultaccessentry': {
'Meta': {'object_name': 'DefaultAccessEntry'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'default_access_entry_class'", 'to': u"orm['contenttypes.ContentType']"}),
'holder_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'holder_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'default_access_entry_holder'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['permissions.StoredPermission']"})
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['permissions.StoredPermission']"})
},
u'contenttypes.contenttype': {
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'permissions.storedpermission': {
'permissions.storedpermission': {
'Meta': {'ordering': "('namespace',)", 'unique_together': "(('namespace', 'name'),)", 'object_name': 'StoredPermission'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'namespace': ('django.db.models.fields.CharField', [], {'max_length': '64'})
}

View File

@@ -8,46 +8,46 @@ class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'CreatorSingleton.lock_id'
db.delete_column(u'acls_creatorsingleton', 'lock_id')
db.delete_column('acls_creatorsingleton', 'lock_id')
def backwards(self, orm):
# Adding field 'CreatorSingleton.lock_id'
db.add_column(u'acls_creatorsingleton', 'lock_id',
db.add_column('acls_creatorsingleton', 'lock_id',
self.gf('django.db.models.fields.CharField')(default='1', max_length=1, unique=True),
keep_default=False)
models = {
u'acls.accessentry': {
'acls.accessentry': {
'Meta': {'object_name': 'AccessEntry'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'object_content_type'", 'to': u"orm['contenttypes.ContentType']"}),
'holder_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'holder_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'access_holder'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['permissions.StoredPermission']"})
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['permissions.StoredPermission']"})
},
u'acls.creatorsingleton': {
'acls.creatorsingleton': {
'Meta': {'object_name': 'CreatorSingleton'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'acls.defaultaccessentry': {
'acls.defaultaccessentry': {
'Meta': {'object_name': 'DefaultAccessEntry'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'default_access_entry_class'", 'to': u"orm['contenttypes.ContentType']"}),
'holder_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'holder_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'default_access_entry_holder'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['permissions.StoredPermission']"})
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['permissions.StoredPermission']"})
},
u'contenttypes.contenttype': {
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'permissions.storedpermission': {
'permissions.storedpermission': {
'Meta': {'ordering': "('namespace',)", 'unique_together': "(('namespace', 'name'),)", 'object_name': 'StoredPermission'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'namespace': ('django.db.models.fields.CharField', [], {'max_length': '64'})
}

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
import logging
from django.core.exceptions import PermissionDenied
@@ -18,7 +20,7 @@ class CheckAccessNode(Node):
def render(self, context):
permission_list = Variable(self.permission_list).resolve(context)
logger.debug('permission_list: %s', u','.join([unicode(p) for p in permission_list]))
logger.debug('permission_list: %s', ','.join([unicode(p) for p in permission_list]))
try:
# Check access_object, useful for document_page views
@@ -29,15 +31,15 @@ class CheckAccessNode(Node):
obj = Variable(self.obj).resolve(context)
logger.debug('obj: %s', obj)
except VariableDoesNotExist:
context[u'access'] = False
context['access'] = False
logger.debug('no obj, access False')
return u''
return ''
if not permission_list:
# There is no permissions list to check against which means
# this link is available for all
context[u'access'] = True
return u''
context['access'] = True
return ''
requester = Variable(self.requester).resolve(context)
logger.debug('requester: %s', requester)
@@ -46,17 +48,17 @@ class CheckAccessNode(Node):
try:
AccessEntry.objects.check_accesses(permission_list, requester, obj)
except PermissionDenied:
context[u'access'] = False
context['access'] = False
logger.debug('access: False')
return u''
return ''
else:
context[u'access'] = True
context['access'] = True
logger.debug('access: True')
return u''
return ''
else:
context[u'access'] = False
context['access'] = False
logger.debug('No object, access: False')
return u''
return ''
@register.tag
@@ -65,6 +67,6 @@ def check_access(parser, token):
# Splitting by None == splitting by spaces.
tag_name, args = token.contents.split(None, 1)
except ValueError:
raise TemplateSyntaxError(u'%r tag requires arguments' % token.contents.split()[0])
raise TemplateSyntaxError('%r tag requires arguments' % token.contents.split()[0])
return CheckAccessNode(*args.split())

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns('acls.views',

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
from json import loads
@@ -30,7 +30,7 @@ logger = logging.getLogger(__name__)
def _permission_titles(permission_list):
return u', '.join([unicode(permission) for permission in permission_list])
return ', '.join([unicode(permission) for permission in permission_list])
def acl_list_for(request, obj, extra_context=None):
@@ -43,10 +43,10 @@ def acl_list_for(request, obj, extra_context=None):
context = {
'object_list': AccessEntry.objects.get_holders_for(obj),
'title': _(u'Access control lists for: %s' % obj),
'title': _('Access control lists for: %s' % obj),
'extra_columns': [
{'name': _(u'Holder'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
{'name': _(u'Permissions'), 'attribute': encapsulate(lambda x: _permission_titles(AccessEntry.objects.get_holder_permissions_for(obj, x.source_object, db_only=True)))},
{'name': _('Holder'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
{'name': _('Permissions'), 'attribute': encapsulate(lambda x: _permission_titles(AccessEntry.objects.get_holder_permissions_for(obj, x.source_object, db_only=True)))},
],
'hide_object': True,
'access_object': AccessObject.encapsulate(obj),
@@ -91,19 +91,19 @@ def acl_detail_for(request, actor, obj):
# TODO : get all globally assigned permission, new function get_permissions_for_holder (roles aware)
subtemplates_list = [
{
'name': u'main/generic_list_subtemplate.html',
'name': 'main/generic_list_subtemplate.html',
'context': {
'title': _(u'Permissions available to: %(actor)s for %(obj)s' % {
'title': _('Permissions available to: %(actor)s for %(obj)s' % {
'actor': actor,
'obj': obj
}
),
'object_list': permission_list,
'extra_columns': [
{'name': _(u'Namespace'), 'attribute': 'namespace'},
{'name': _(u'Label'), 'attribute': 'label'},
{'name': _('Namespace'), 'attribute': 'namespace'},
{'name': _('Label'), 'attribute': 'label'},
{
'name': _(u'Has permission'),
'name': _('Has permission'),
'attribute': encapsulate(lambda permission: two_state_template(AccessEntry.objects.has_access(permission, actor, obj, db_only=True)))
},
],
@@ -176,27 +176,27 @@ def acl_grant(request):
for requester, obj_ps in items.items():
for obj, ps in obj_ps.items():
title_suffix.append(_(u', ').join([u'"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(u' for %s') % obj)
title_suffix.append(_(u' to %s') % requester)
title_suffix.append(_(', ').join(['"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(' for %s') % obj)
title_suffix.append(_(' to %s') % requester)
if len(items_property_list) == 1:
title_prefix = _(u'Are you sure you wish to grant the permission %(title_suffix)s?')
title_prefix = _('Are you sure you wish to grant the permission %(title_suffix)s?')
else:
title_prefix = _(u'Are you sure you wish to grant the permissions %(title_suffix)s?')
title_prefix = _('Are you sure you wish to grant the permissions %(title_suffix)s?')
if request.method == 'POST':
for requester, object_permissions in items.items():
for obj, permissions in object_permissions.items():
for permission in permissions:
if AccessEntry.objects.grant(permission, requester.source_object, obj.source_object):
messages.success(request, _(u'Permission "%(permission)s" granted to %(actor)s for %(object)s.') % {
messages.success(request, _('Permission "%(permission)s" granted to %(actor)s for %(object)s.') % {
'permission': permission,
'actor': requester,
'object': obj
})
else:
messages.warning(request, _(u'%(actor)s, already had the permission "%(permission)s" granted for %(object)s.') % {
messages.warning(request, _('%(actor)s, already had the permission "%(permission)s" granted for %(object)s.') % {
'actor': requester,
'permission': permission,
'object': obj,
@@ -211,7 +211,7 @@ def acl_grant(request):
}
context['title'] = title_prefix % {
'title_suffix': u''.join(title_suffix),
'title_suffix': ''.join(title_suffix),
}
logger.debug('navigation_object_count: %d', navigation_object_count)
@@ -268,27 +268,27 @@ def acl_revoke(request):
for requester, obj_ps in items.items():
for obj, ps in obj_ps.items():
title_suffix.append(_(u', ').join([u'"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(u' for %s') % obj)
title_suffix.append(_(u' from %s') % requester)
title_suffix.append(_(', ').join(['"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(' for %s') % obj)
title_suffix.append(_(' from %s') % requester)
if len(items_property_list) == 1:
title_prefix = _(u'Are you sure you wish to revoke the permission %(title_suffix)s?')
title_prefix = _('Are you sure you wish to revoke the permission %(title_suffix)s?')
else:
title_prefix = _(u'Are you sure you wish to revoke the permissions %(title_suffix)s?')
title_prefix = _('Are you sure you wish to revoke the permissions %(title_suffix)s?')
if request.method == 'POST':
for requester, object_permissions in items.items():
for obj, permissions in object_permissions.items():
for permission in permissions:
if AccessEntry.objects.revoke(permission, requester.source_object, obj.source_object):
messages.success(request, _(u'Permission "%(permission)s" revoked of %(actor)s for %(object)s.') % {
messages.success(request, _('Permission "%(permission)s" revoked of %(actor)s for %(object)s.') % {
'permission': permission,
'actor': requester,
'object': obj
})
else:
messages.warning(request, _(u'%(actor)s, didn\'t had the permission "%(permission)s" for %(object)s.') % {
messages.warning(request, _('%(actor)s, didn\'t had the permission "%(permission)s" for %(object)s.') % {
'actor': requester,
'permission': permission,
'object': obj,
@@ -303,7 +303,7 @@ def acl_revoke(request):
}
context['title'] = title_prefix % {
'title_suffix': u''.join(title_suffix),
'title_suffix': ''.join(title_suffix),
}
logger.debug('navigation_object_count: %d', navigation_object_count)
@@ -328,10 +328,10 @@ def acl_new_holder_for(request, obj, extra_context=None, navigation_object=None)
access_object = AccessObject.encapsulate(obj)
access_holder = AccessHolder.get(form.cleaned_data['holder_gid'])
query_string = {u'navigation_object': navigation_object}
query_string = {'navigation_object': navigation_object}
return HttpResponseRedirect(
u'%s?%s' % (
'%s?%s' % (
reverse('acls:acl_detail', args=[access_object.gid, access_holder.gid]),
urlencode(query_string)
)
@@ -343,8 +343,8 @@ def acl_new_holder_for(request, obj, extra_context=None, navigation_object=None)
context = {
'form': form,
'title': _(u'Add new holder for: %s') % obj,
'submit_label': _(u'Select'),
'title': _('Add new holder for: %s') % obj,
'submit_label': _('Select'),
'submit_icon_famfam': 'tick',
'object': obj,
'access_object': AccessObject.encapsulate(obj),
@@ -376,9 +376,9 @@ def acl_setup_valid_classes(request):
context = {
'object_list': DefaultAccessEntry.get_classes(),
'title': _(u'Classes'),
'title': _('Classes'),
'extra_columns': [
{'name': _(u'Class'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
{'name': _('Class'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
],
'hide_object': True,
}
@@ -397,10 +397,10 @@ def acl_class_acl_list(request, access_object_class_gid):
context = {
'object_list': DefaultAccessEntry.objects.get_holders_for(access_object_class.source_object),
'title': _(u'Default access control lists for class: %s') % access_object_class,
'title': _('Default access control lists for class: %s') % access_object_class,
'extra_columns': [
{'name': _(u'Holder'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
{'name': _(u'Permissions'), 'attribute': encapsulate(lambda x: _permission_titles(DefaultAccessEntry.objects.get_holder_permissions_for(access_object_class.source_object, x.source_object)))},
{'name': _('Holder'), 'attribute': encapsulate(lambda x: object_w_content_type_icon(x.source_object))},
{'name': _('Permissions'), 'attribute': encapsulate(lambda x: _permission_titles(DefaultAccessEntry.objects.get_holder_permissions_for(access_object_class.source_object, x.source_object)))},
],
'hide_object': True,
'access_object_class': access_object_class,
@@ -423,18 +423,18 @@ def acl_class_acl_detail(request, access_object_class_gid, holder_object_gid):
# TODO : get all globally assigned permission, new function get_permissions_for_holder (roles aware)
subtemplates_list = [
{
'name': u'main/generic_list_subtemplate.html',
'name': 'main/generic_list_subtemplate.html',
'context': {
'title': _(u'Permissions available to: %(actor)s for class %(class)s' % {
'title': _('Permissions available to: %(actor)s for class %(class)s' % {
'actor': actor,
'class': access_object_class
}),
'object_list': permission_list,
'extra_columns': [
{'name': _(u'Namespace'), 'attribute': 'namespace'},
{'name': _(u'Label'), 'attribute': 'label'},
{'name': _('Namespace'), 'attribute': 'namespace'},
{'name': _('Label'), 'attribute': 'label'},
{
'name': _(u'Has permission'),
'name': _('Has permission'),
'attribute': encapsulate(lambda x: two_state_template(DefaultAccessEntry.objects.has_access(x, actor.source_object, access_object_class.source_object)))
},
],
@@ -472,9 +472,9 @@ def acl_class_new_holder_for(request, access_object_class_gid):
context = {
'form': form,
'title': _(u'Add new holder for class: %s') % unicode(access_object_class),
'title': _('Add new holder for class: %s') % unicode(access_object_class),
'object': access_object_class,
'submit_label': _(u'Select'),
'submit_label': _('Select'),
'submit_icon_famfam': 'tick'
}
@@ -513,27 +513,27 @@ def acl_class_multiple_grant(request):
for requester, obj_ps in items.items():
for obj, ps in obj_ps.items():
title_suffix.append(_(u', ').join([u'"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(u' for %s') % obj)
title_suffix.append(_(u' to %s') % requester)
title_suffix.append(_(', ').join(['"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(' for %s') % obj)
title_suffix.append(_(' to %s') % requester)
if len(items_property_list) == 1:
title_prefix = _(u'Are you sure you wish to grant the permission %(title_suffix)s?')
title_prefix = _('Are you sure you wish to grant the permission %(title_suffix)s?')
else:
title_prefix = _(u'Are you sure you wish to grant the permissions %(title_suffix)s?')
title_prefix = _('Are you sure you wish to grant the permissions %(title_suffix)s?')
if request.method == 'POST':
for requester, object_permissions in items.items():
for obj, permissions in object_permissions.items():
for permission in permissions:
if DefaultAccessEntry.objects.grant(permission, requester.source_object, obj.source_object):
messages.success(request, _(u'Permission "%(permission)s" granted to %(actor)s for %(object)s.') % {
messages.success(request, _('Permission "%(permission)s" granted to %(actor)s for %(object)s.') % {
'permission': permission,
'actor': requester,
'object': obj
})
else:
messages.warning(request, _(u'%(actor)s, already had the permission "%(permission)s" granted for %(object)s.') % {
messages.warning(request, _('%(actor)s, already had the permission "%(permission)s" granted for %(object)s.') % {
'actor': requester,
'permission': permission,
'object': obj,
@@ -548,7 +548,7 @@ def acl_class_multiple_grant(request):
}
context['title'] = title_prefix % {
'title_suffix': u''.join(title_suffix),
'title_suffix': ''.join(title_suffix),
}
logger.debug('navigation_object_count: %d', navigation_object_count)
@@ -591,27 +591,27 @@ def acl_class_multiple_revoke(request):
for requester, obj_ps in items.items():
for obj, ps in obj_ps.items():
title_suffix.append(_(u', ').join([u'"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(u' for %s') % obj)
title_suffix.append(_(u' from %s') % requester)
title_suffix.append(_(', ').join(['"%s"' % unicode(p) for p in ps]))
title_suffix.append(_(' for %s') % obj)
title_suffix.append(_(' from %s') % requester)
if len(items_property_list) == 1:
title_prefix = _(u'Are you sure you wish to revoke the permission %(title_suffix)s?')
title_prefix = _('Are you sure you wish to revoke the permission %(title_suffix)s?')
else:
title_prefix = _(u'Are you sure you wish to revoke the permissions %(title_suffix)s?')
title_prefix = _('Are you sure you wish to revoke the permissions %(title_suffix)s?')
if request.method == 'POST':
for requester, object_permissions in items.items():
for obj, permissions in object_permissions.items():
for permission in permissions:
if DefaultAccessEntry.objects.revoke(permission, requester.source_object, obj.source_object):
messages.success(request, _(u'Permission "%(permission)s" revoked of %(actor)s for %(object)s.') % {
messages.success(request, _('Permission "%(permission)s" revoked of %(actor)s for %(object)s.') % {
'permission': permission,
'actor': requester,
'object': obj
})
else:
messages.warning(request, _(u'%(actor)s, didn\'t had the permission "%(permission)s" for %(object)s.') % {
messages.warning(request, _('%(actor)s, didn\'t had the permission "%(permission)s" for %(object)s.') % {
'actor': requester,
'permission': permission,
'object': obj,
@@ -626,7 +626,7 @@ def acl_class_multiple_revoke(request):
}
context['title'] = title_prefix % {
'title_suffix': u''.join(title_suffix),
'title_suffix': ''.join(title_suffix),
}
logger.debug('navigation_object_count: %d', navigation_object_count)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.safestring import mark_safe
from django.contrib.contenttypes.models import ContentType
@@ -8,7 +8,7 @@ from .literals import CONTENT_TYPE_ICON_MAP
def content_type_icon(content_type):
return mark_safe(u'<span class="famfam active famfam-%s"></span>' % CONTENT_TYPE_ICON_MAP.get('%s.%s' % (content_type.app_label, content_type.model), 'help'))
return mark_safe('<span class="famfam active famfam-%s"></span>' % CONTENT_TYPE_ICON_MAP.get('%s.%s' % (content_type.app_label, content_type.model), 'help'))
def object_w_content_type_icon(obj):

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from datetime import timedelta

View File

@@ -1,9 +1,10 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import pytz
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
import pytz
from rest_framework import generics, status
from rest_framework.response import Response

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.utils.translation import ugettext

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django import forms

View File

@@ -1,8 +1,11 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from .permissions import (PERMISSION_DOCUMENT_CHECKOUT, PERMISSION_DOCUMENT_CHECKIN, PERMISSION_DOCUMENT_CHECKIN_OVERRIDE)
from .permissions import (
PERMISSION_DOCUMENT_CHECKOUT, PERMISSION_DOCUMENT_CHECKIN,
PERMISSION_DOCUMENT_CHECKIN_OVERRIDE
)
def is_checked_out(context):
@@ -13,7 +16,7 @@ def is_not_checked_out(context):
return not context['object'].is_checked_out()
checkout_list = {'text': _(u'Checkouts'), 'view': 'checkouts:checkout_list', 'famfam': 'basket'}
checkout_list = {'text': _('Checkouts'), 'view': 'checkouts:checkout_list', 'famfam': 'basket'}
checkout_document = {'text': _('Check out document'), 'view': 'checkouts:checkout_document', 'args': 'object.pk', 'famfam': 'basket_put', 'condition': is_not_checked_out, 'permissions': [PERMISSION_DOCUMENT_CHECKOUT]}
checkin_document = {'text': _('Check in document'), 'view': 'checkouts:checkin_document', 'args': 'object.pk', 'famfam': 'basket_remove', 'condition': is_checked_out, 'permissions': [PERMISSION_DOCUMENT_CHECKIN, PERMISSION_DOCUMENT_CHECKIN_OVERRIDE]}
checkout_info = {'text': _('Check in/out'), 'view': 'checkouts:checkout_info', 'args': 'object.pk', 'famfam': 'basket', 'permissions': [PERMISSION_DOCUMENT_CHECKIN, PERMISSION_DOCUMENT_CHECKIN_OVERRIDE, PERMISSION_DOCUMENT_CHECKOUT]}

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
@@ -6,6 +6,6 @@ STATE_CHECKED_OUT = 'checkedout'
STATE_CHECKED_IN = 'checkedin'
STATE_LABELS = {
STATE_CHECKED_OUT: _(u'Checked out'),
STATE_CHECKED_IN: _(u'Checked in/available'),
STATE_CHECKED_OUT: _('Checked out'),
STATE_CHECKED_IN: _('Checked in/available'),
}

View File

@@ -1,9 +1,9 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
from django.db import models
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.timezone import now
from acls.models import AccessEntry

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
@@ -20,16 +20,16 @@ class DocumentCheckout(models.Model):
"""
Model to store the state and information of a document checkout
"""
document = models.ForeignKey(Document, verbose_name=_(u'Document'), unique=True)
checkout_datetime = models.DateTimeField(verbose_name=_(u'Check out date and time'), auto_now_add=True)
expiration_datetime = models.DateTimeField(verbose_name=_(u'Check out expiration date and time'), help_text=_(u'Amount of time to hold the document checked out in minutes.'))
document = models.ForeignKey(Document, verbose_name=_('Document'), unique=True)
checkout_datetime = models.DateTimeField(verbose_name=_('Check out date and time'), auto_now_add=True)
expiration_datetime = models.DateTimeField(verbose_name=_('Check out expiration date and time'), help_text=_('Amount of time to hold the document checked out in minutes.'))
# TODO: simplify user_object to an instance of User
user_content_type = models.ForeignKey(ContentType, null=True, blank=True) # blank and null added for ease of db migration
user_object_id = models.PositiveIntegerField(null=True, blank=True)
user_object = generic.GenericForeignKey(ct_field='user_content_type', fk_field='user_object_id')
block_new_version = models.BooleanField(default=True, verbose_name=_(u'Block new version upload'), help_text=_(u'Do not allow new version of this document to be uploaded.'))
block_new_version = models.BooleanField(default=True, verbose_name=_('Block new version upload'), help_text=_('Do not allow new version of this document to be uploaded.'))
# block_metadata
# block_editing
@@ -55,5 +55,5 @@ class DocumentCheckout(models.Model):
return ('checkout:checkout_info', [self.document.pk])
class Meta:
verbose_name = _(u'Document checkout')
verbose_name_plural = _(u'Document checkouts')
verbose_name = _('Document checkout')
verbose_name_plural = _('Document checkouts')

View File

@@ -1,12 +1,12 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
namespace = PermissionNamespace('checkouts', _(u'Document checkout'))
namespace = PermissionNamespace('checkouts', _('Document checkout'))
PERMISSION_DOCUMENT_CHECKOUT = Permission.objects.register(namespace, 'checkout_document', _(u'Check out documents'))
PERMISSION_DOCUMENT_CHECKIN = Permission.objects.register(namespace, 'checkin_document', _(u'Check in documents'))
PERMISSION_DOCUMENT_CHECKIN_OVERRIDE = Permission.objects.register(namespace, 'checkin_document_override', _(u'Forcefully check in documents'))
PERMISSION_DOCUMENT_RESTRICTIONS_OVERRIDE = Permission.objects.register(namespace, 'checkout_restrictions_override', _(u'Allow overriding check out restrictions'))
PERMISSION_DOCUMENT_CHECKOUT = Permission.objects.register(namespace, 'checkout_document', _('Check out documents'))
PERMISSION_DOCUMENT_CHECKIN = Permission.objects.register(namespace, 'checkin_document', _('Check in documents'))
PERMISSION_DOCUMENT_CHECKIN_OVERRIDE = Permission.objects.register(namespace, 'checkin_document_override', _('Forcefully check in documents'))
PERMISSION_DOCUMENT_RESTRICTIONS_OVERRIDE = Permission.objects.register(namespace, 'checkout_restrictions_override', _('Allow overriding check out restrictions'))

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from rest_framework import serializers

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
@@ -14,7 +14,7 @@ logger = logging.getLogger(__name__)
@app.task(ignore_result=True)
def task_check_expired_check_outs():
logger.debug('executing...')
lock_id = u'task_expired_check_outs'
lock_id = 'task_expired_check_outs'
try:
logger.debug('trying to acquire lock: %s', lock_id)
lock = Lock.acquire_lock(lock_id, LOCK_EXPIRE)

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from .api_views import APICheckedoutDocumentListView, APICheckedoutDocumentView

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.contrib import messages
from django.core.exceptions import PermissionDenied
@@ -12,8 +12,7 @@ from documents.models import Document
from documents.views import document_list
from acls.models import AccessEntry
from common.utils import get_object_name
from common.utils import encapsulate
from common.utils import encapsulate, get_object_name
from permissions.models import Permission
from .exceptions import DocumentAlreadyCheckedOut, DocumentNotCheckedOut
@@ -29,12 +28,12 @@ def checkout_list(request):
return document_list(
request,
object_list=DocumentCheckout.objects.checked_out_documents(),
title=_(u'Documents checked out'),
title=_('Documents checked out'),
extra_context={
'extra_columns': [
{'name': _(u'Checkout user'), 'attribute': encapsulate(lambda document: get_object_name(document.checkout_info().user_object, display_object_type=False))},
{'name': _(u'Checkout time and date'), 'attribute': encapsulate(lambda document: document.checkout_info().checkout_datetime)},
{'name': _(u'Checkout expiration'), 'attribute': encapsulate(lambda document: document.checkout_info().expiration_datetime)},
{'name': _('Checkout user'), 'attribute': encapsulate(lambda document: get_object_name(document.checkout_info().user_object, display_object_type=False))},
{'name': _('Checkout time and date'), 'attribute': encapsulate(lambda document: document.checkout_info().checkout_datetime)},
{'name': _('Checkout expiration'), 'attribute': encapsulate(lambda document: document.checkout_info().expiration_datetime)},
],
}
)
@@ -47,19 +46,19 @@ def checkout_info(request, document_pk):
except PermissionDenied:
AccessEntry.objects.check_accesses([PERMISSION_DOCUMENT_CHECKOUT, PERMISSION_DOCUMENT_CHECKIN], request.user, document)
paragraphs = [_(u'Document status: %s') % STATE_LABELS[document.checkout_state()]]
paragraphs = [_('Document status: %s') % STATE_LABELS[document.checkout_state()]]
if document.is_checked_out():
checkout_info = document.checkout_info()
paragraphs.append(_(u'User: %s') % get_object_name(checkout_info.user_object, display_object_type=False))
paragraphs.append(_(u'Check out time: %s') % checkout_info.checkout_datetime)
paragraphs.append(_(u'Check out expiration: %s') % checkout_info.expiration_datetime)
paragraphs.append(_(u'New versions allowed: %s') % (_(u'Yes') if not checkout_info.block_new_version else _(u'No')))
paragraphs.append(_('User: %s') % get_object_name(checkout_info.user_object, display_object_type=False))
paragraphs.append(_('Check out time: %s') % checkout_info.checkout_datetime)
paragraphs.append(_('Check out expiration: %s') % checkout_info.expiration_datetime)
paragraphs.append(_('New versions allowed: %s') % (_('Yes') if not checkout_info.block_new_version else _('No')))
return render_to_response('main/generic_template.html', {
'paragraphs': paragraphs,
'object': document,
'title': _(u'Document check out details')
'title': _('Document check out details')
}, context_instance=RequestContext(request))
@@ -79,12 +78,12 @@ def checkout_document(request, document_pk):
document_checkout.document = document
document_checkout.save()
except DocumentAlreadyCheckedOut:
messages.error(request, _(u'Document already checked out.'))
messages.error(request, _('Document already checked out.'))
return HttpResponseRedirect(reverse('checkouts:checkout_info', args=[document.pk]))
except Exception as exception:
messages.error(request, _(u'Error trying to check out document; %s') % exception)
messages.error(request, _('Error trying to check out document; %s') % exception)
else:
messages.success(request, _(u'Document "%s" checked out successfully.') % document)
messages.success(request, _('Document "%s" checked out successfully.') % document)
return HttpResponseRedirect(reverse('checkouts:checkout_info', args=[document.pk]))
else:
form = DocumentCheckoutForm(initial={'document': document})
@@ -92,7 +91,7 @@ def checkout_document(request, document_pk):
return render_to_response('main/generic_form.html', {
'form': form,
'object': document,
'title': _(u'Document check out')
'title': _('Document check out')
}, context_instance=RequestContext(request))
@@ -104,7 +103,7 @@ def checkin_document(request, document_pk):
next = request.POST.get('next', request.GET.get('next', post_action_redirect if post_action_redirect else request.META.get('HTTP_REFERER', reverse('main:home'))))
if not document.is_checked_out():
messages.error(request, _(u'Document has not been checked out.'))
messages.error(request, _('Document has not been checked out.'))
return HttpResponseRedirect(previous)
# If the user trying to check in the document is the same as the check out
@@ -125,11 +124,11 @@ def checkin_document(request, document_pk):
try:
document.check_in(user=request.user)
except DocumentNotCheckedOut:
messages.error(request, _(u'Document has not been checked out.'))
messages.error(request, _('Document has not been checked out.'))
except Exception as exception:
messages.error(request, _(u'Error trying to check in document; %s') % exception)
messages.error(request, _('Error trying to check in document; %s') % exception)
else:
messages.success(request, _(u'Document "%s" checked in successfully.') % document)
messages.success(request, _('Document "%s" checked in successfully.') % document)
return HttpResponseRedirect(next)
context = {
@@ -140,9 +139,9 @@ def checkin_document(request, document_pk):
}
if document.checkout_info().user_object != request.user:
context['title'] = _(u'You didn\'t originally checked out this document. Are you sure you wish to forcefully check in document: %s?') % document
context['title'] = _('You didn\'t originally checked out this document. Are you sure you wish to forcefully check in document: %s?') % document
else:
context['title'] = _(u'Are you sure you wish to check in document: %s?') % document
context['title'] = _('Are you sure you wish to check in document: %s?') % document
return render_to_response('main/generic_confirm.html', context,
context_instance=RequestContext(request))

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
@@ -14,9 +14,9 @@ class SplitDeltaWidget(forms.widgets.MultiWidget):
"""
def __init__(self, attrs=None):
widgets = (
forms.widgets.TextInput(attrs={'maxlength': 3, 'style': 'width: 5em;', 'placeholder': _(u'Days')}),
forms.widgets.TextInput(attrs={'maxlength': 4, 'style': 'width: 5em;', 'placeholder': _(u'Hours')}),
forms.widgets.TextInput(attrs={'maxlength': 5, 'style': 'width: 5em;', 'placeholder': _(u'Minutes')}),
forms.widgets.TextInput(attrs={'maxlength': 3, 'style': 'width: 5em;', 'placeholder': _('Days')}),
forms.widgets.TextInput(attrs={'maxlength': 4, 'style': 'width: 5em;', 'placeholder': _('Hours')}),
forms.widgets.TextInput(attrs={'maxlength': 5, 'style': 'width: 5em;', 'placeholder': _('Minutes')}),
)
super(SplitDeltaWidget, self).__init__(widgets, attrs)
@@ -46,10 +46,10 @@ class SplitTimeDeltaField(forms.MultiValueField):
widget = SplitDeltaWidget
hidden_widget = SplitHiddenDeltaWidget
default_error_messages = {
'invalid_days': _(u'Enter a valid number of days.'),
'invalid_hours': _(u'Enter a valid number of hours.'),
'invalid_minutes': _(u'Enter a valid number of minutes.'),
'invalid_timedelta': _(u'Enter a valid time difference.'),
'invalid_days': _('Enter a valid number of days.'),
'invalid_hours': _('Enter a valid number of hours.'),
'invalid_minutes': _('Enter a valid number of minutes.'),
'invalid_timedelta': _('Enter a valid time difference.'),
}
def __init__(self, *args, **kwargs):
@@ -75,7 +75,7 @@ class SplitTimeDeltaField(forms.MultiValueField):
),
)
super(SplitTimeDeltaField, self).__init__(fields, *args, **kwargs)
self.help_text = _(u'Amount of time to hold the document in the checked out state in days, hours and/or minutes.')
self.help_text = _('Amount of time to hold the document in the checked out state in days, hours and/or minutes.')
self.label = _('Check out expiration date and time')
def compress(self, data_list):

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
import tempfile
@@ -6,16 +6,15 @@ import tempfile
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from south.signals import post_migrate
from common import settings as common_settings
from navigation.api import register_links, register_top_menu
from common import settings as common_settings
from .links import (link_about, link_current_user_details,
link_current_user_edit,
link_current_user_locale_profile_details,

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext
@@ -39,7 +41,7 @@ class ModelAttribute(object):
def get_display(self, show_name=False):
if self.description:
return u'{} - {}'.format(self.name if show_name else self.label, self.description)
return '{} - {}'.format(self.name if show_name else self.label, self.description)
else:
return unicode(self.name if show_name else self.label)

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
import zipfile
try:

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import warnings
import os
@@ -95,7 +95,7 @@ class ChoiceForm(forms.Form):
"""
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', [])
label = kwargs.pop('label', _(u'Selection'))
label = kwargs.pop('label', _('Selection'))
super(ChoiceForm, self).__init__(*args, **kwargs)
self.fields['selection'].choices = choices
self.fields['selection'].label = label
@@ -140,15 +140,15 @@ class EmailAuthenticationForm(forms.Form):
"""
A form to use email address authentication
"""
email = forms.CharField(label=_(u'Email'), max_length=254,
email = forms.CharField(label=_('Email'), max_length=254,
widget=EmailInput()
)
password = forms.CharField(label=_(u'Password'), widget=forms.PasswordInput)
password = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
error_messages = {
'invalid_login': _(u'Please enter a correct email and password. '
u'Note that the password field is case-sensitive.'),
'inactive': _(u'This account is inactive.'),
'invalid_login': _('Please enter a correct email and password. '
'Note that the password field is case-sensitive.'),
'inactive': _('This account is inactive.'),
}
def __init__(self, request=None, *args, **kwargs):
@@ -193,7 +193,7 @@ class EmailAuthenticationForm(forms.Form):
class FileDisplayForm(forms.Form):
text = forms.CharField(
label='', # _(u'Text'),
label='', # _('Text'),
widget=forms.widgets.Textarea(
attrs={'cols': 40, 'rows': 20, 'readonly': 'readonly'}
)
@@ -208,5 +208,5 @@ class FileDisplayForm(forms.Form):
class LicenseForm(FileDisplayForm):
FILENAME = u'LICENSE'
FILENAME = 'LICENSE'
DIRECTORY = []

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
@@ -7,14 +7,14 @@ def has_usable_password(context):
return context['request'].user.has_usable_password
link_password_change = {'text': _(u'Change password'), 'view': 'common:password_change_view', 'famfam': 'computer_key', 'condition': has_usable_password}
link_current_user_details = {'text': _(u'User details'), 'view': 'common:current_user_details', 'famfam': 'vcard'}
link_current_user_edit = {'text': _(u'Edit details'), 'view': 'common:current_user_edit', 'famfam': 'vcard_edit'}
link_password_change = {'text': _('Change password'), 'view': 'common:password_change_view', 'famfam': 'computer_key', 'condition': has_usable_password}
link_current_user_details = {'text': _('User details'), 'view': 'common:current_user_details', 'famfam': 'vcard'}
link_current_user_edit = {'text': _('Edit details'), 'view': 'common:current_user_edit', 'famfam': 'vcard_edit'}
link_about = {'text': _(u'About'), 'view': 'common:about_view', 'famfam': 'information'}
link_license = {'text': _(u'License'), 'view': 'common:license_view', 'famfam': 'script'}
link_about = {'text': _('About'), 'view': 'common:about_view', 'famfam': 'information'}
link_license = {'text': _('License'), 'view': 'common:license_view', 'famfam': 'script'}
link_current_user_locale_profile_details = {'text': _(u'Locale profile'), 'view': 'common:current_user_locale_profile_details', 'famfam': 'world'}
link_current_user_locale_profile_edit = {'text': _(u'Edit locale profile'), 'view': 'common:current_user_locale_profile_edit', 'famfam': 'world_edit'}
link_current_user_locale_profile_details = {'text': _('Locale profile'), 'view': 'common:current_user_locale_profile_details', 'famfam': 'world'}
link_current_user_locale_profile_edit = {'text': _('Edit locale profile'), 'view': 'common:current_user_locale_profile_edit', 'famfam': 'world_edit'}
link_logout = {'text': _(u'Logout'), 'view': 'common:logout_view', 'famfam': 'door_out'}
link_logout = {'text': _('Logout'), 'view': 'common:logout_view', 'famfam': 'door_out'}

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AnonymousUser

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import re

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.utils.html import strip_spaces_between_tags

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
import pytz
from django.utils import timezone

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from pytz import common_timezones
@@ -18,7 +18,7 @@ SHARED_UPLOADED_FILE_PATH = 'shared_uploads'
def upload_to(instance, filename):
instance.filename = filename
return u'/'.join([SHARED_UPLOADED_FILE_PATH, filename])
return '/'.join([SHARED_UPLOADED_FILE_PATH, filename])
class AnonymousUserSingleton(SingletonModel):
@@ -28,26 +28,26 @@ class AnonymousUserSingleton(SingletonModel):
return ugettext('Anonymous user')
class Meta:
verbose_name = verbose_name_plural = _(u'Anonymous user')
verbose_name = verbose_name_plural = _('Anonymous user')
class AutoAdminSingleton(SingletonModel):
account = models.ForeignKey(User, null=True, blank=True, related_name='auto_admin_account', verbose_name=_(u'Account'))
password = models.CharField(null=True, blank=True, verbose_name=_(u'Password'), max_length=128)
password_hash = models.CharField(null=True, blank=True, verbose_name=_(u'Password hash'), max_length=128)
account = models.ForeignKey(User, null=True, blank=True, related_name='auto_admin_account', verbose_name=_('Account'))
password = models.CharField(null=True, blank=True, verbose_name=_('Password'), max_length=128)
password_hash = models.CharField(null=True, blank=True, verbose_name=_('Password hash'), max_length=128)
class Meta:
verbose_name = verbose_name_plural = _(u'Auto admin properties')
verbose_name = verbose_name_plural = _('Auto admin properties')
class SharedUploadedFile(models.Model):
file = models.FileField(upload_to=upload_to, storage=shared_storage_backend, verbose_name=_(u'File'))
file = models.FileField(upload_to=upload_to, storage=shared_storage_backend, verbose_name=_('File'))
filename = models.CharField(max_length=255, verbose_name=_('Filename'))
datatime = models.DateTimeField(auto_now_add=True, verbose_name=_('Date time'))
class Meta:
verbose_name = _(u'Shared uploaded file')
verbose_name_plural = _(u'Shared uploaded files')
verbose_name = _('Shared uploaded file')
verbose_name_plural = _('Shared uploaded files')
def __unicode__(self):
return self.filename
@@ -67,5 +67,5 @@ class UserLocaleProfile(models.Model):
return unicode(self.user)
class Meta:
verbose_name = _(u'User locale profile')
verbose_name_plural = _(u'User locale profiles')
verbose_name = _('User locale profile')
verbose_name_plural = _('User locale profiles')

View File

@@ -1,5 +1,3 @@
from __future__ import absolute_import
from common.utils import load_backend
from .settings import SHARED_STORAGE

View File

@@ -1,67 +1,67 @@
"""Configuration options for the common app"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from smart_settings.api import register_setting
TEMPORARY_DIRECTORY = register_setting(
namespace=u'common',
module=u'common.settings',
name=u'TEMPORARY_DIRECTORY',
global_name=u'COMMON_TEMPORARY_DIRECTORY',
default=u'/tmp',
description=_(u'Temporary directory used site wide to store thumbnails, previews and temporary files. If none is specified, one will be created using tempfile.mkdtemp()'),
namespace='common',
module='common.settings',
name='TEMPORARY_DIRECTORY',
global_name='COMMON_TEMPORARY_DIRECTORY',
default='/tmp',
description=_('Temporary directory used site wide to store thumbnails, previews and temporary files. If none is specified, one will be created using tempfile.mkdtemp()'),
exists=True
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'AUTO_CREATE_ADMIN',
global_name=u'COMMON_AUTO_CREATE_ADMIN',
namespace='common',
module='common.settings',
name='AUTO_CREATE_ADMIN',
global_name='COMMON_AUTO_CREATE_ADMIN',
default=True,
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'AUTO_ADMIN_USERNAME',
global_name=u'COMMON_AUTO_ADMIN_USERNAME',
default=u'admin',
namespace='common',
module='common.settings',
name='AUTO_ADMIN_USERNAME',
global_name='COMMON_AUTO_ADMIN_USERNAME',
default='admin',
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'AUTO_ADMIN_PASSWORD',
global_name=u'COMMON_AUTO_ADMIN_PASSWORD',
namespace='common',
module='common.settings',
name='AUTO_ADMIN_PASSWORD',
global_name='COMMON_AUTO_ADMIN_PASSWORD',
default=User.objects.make_random_password(),
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'LOGIN_METHOD',
global_name=u'COMMON_LOGIN_METHOD',
default=u'username',
description=_(u'Controls the mechanism used to authenticated user. Options are: username, email'),
namespace='common',
module='common.settings',
name='LOGIN_METHOD',
global_name='COMMON_LOGIN_METHOD',
default='username',
description=_('Controls the mechanism used to authenticated user. Options are: username, email'),
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'ALLOW_ANONYMOUS_ACCESS',
global_name=u'COMMON_ALLOW_ANONYMOUS_ACCESS',
namespace='common',
module='common.settings',
name='ALLOW_ANONYMOUS_ACCESS',
global_name='COMMON_ALLOW_ANONYMOUS_ACCESS',
default=False,
description=_(u'Allow non authenticated users, access to all views'),
description=_('Allow non authenticated users, access to all views'),
)
register_setting(
namespace=u'common',
module=u'common.settings',
name=u'SHARED_STORAGE',
global_name=u'COMMON_SHARED_STORAGE',
namespace='common',
module='common.settings',
name='SHARED_STORAGE',
global_name='COMMON_SHARED_STORAGE',
default='storage.backends.filebasedstorage.FileBasedStorage',
description=_(u'A storage backend that all workers can use to share files.'),
description=_('A storage backend that all workers can use to share files.'),
)

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.template import Library
from common.models import AutoAdminSingleton
@@ -8,4 +10,4 @@ register = Library()
@register.simple_tag(takes_context=True)
def auto_admin_properties(context):
context['auto_admin_properties'] = AutoAdminSingleton.objects.get()
return u''
return ''

View File

@@ -1,5 +1,3 @@
from __future__ import absolute_import
from json import dumps
from django.template import Library

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.template import Library
register = Library()
@@ -5,4 +7,4 @@ register = Library()
@register.filter
def make_non_breakable(value):
return value.replace(u'-', u'\u2011')
return value.replace('-', '\u2011')

View File

@@ -1,5 +1,5 @@
from django.template import Library
from django.conf import settings
from django.template import Library
register = Library()

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django import template
register = template.Library()
@@ -16,7 +18,7 @@ class SetVarNode(template.Node):
# Make it global across all blocks
context.dicts[0][self.var_name] = value
return u""
return ''
def set_var(parser, token):

View File

@@ -1,8 +1,9 @@
from __future__ import unicode_literals
import re
from django.template import Node
from django.template import TemplateSyntaxError, Library
from django.conf import settings
from django.template import Library, Node, TemplateSyntaxError
register = Library()

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
import re
from django.template import (Context, Library, Node, TemplateSyntaxError,

View File

@@ -14,7 +14,7 @@ class CopyNode(Node):
def render(self, context):
context[Variable(self.var_name).resolve(context)] = Variable(self.source_variable).resolve(context)
if self.delete_old:
context[Variable(self.source_variable).resolve(context)] = u''
context[Variable(self.source_variable).resolve(context)] = ''
return ''

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.template import Library
from django.utils.importlib import import_module
@@ -10,4 +12,4 @@ def app_version(app_name):
app = import_module(app_name)
return app.__version__
except ImportError:
return u''
return ''

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, url
from django.views.generic import RedirectView, TemplateView

View File

@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import os
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
def urlquote(link=None, get=None):
u"""
"""
This method does both: urlquote() and urlencode()
urlqoute(): Quote special characters in 'link'
@@ -44,7 +44,7 @@ def urlquote(link=None, get=None):
assert not get, get
get = link
link = ''
assert isinstance(get, dict), u'wrong type "%s", dict required' % type(get)
assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
# assert not (link.startswith('http://') or link.startswith('https://')), \
# 'This method should only quote the url path.
# It should not start with http(s):// (%s)' % (
@@ -54,8 +54,8 @@ def urlquote(link=None, get=None):
if isinstance(get, MultiValueDict):
get = get.lists()
if link:
link = u'%s?' % django_urlquote(link)
return u'%s%s' % (link, django_urlencode(get, doseq=True))
link = '%s?' % django_urlquote(link)
return '%s%s' % (link, django_urlencode(get, doseq=True))
else:
return django_urlquote(link)
@@ -67,7 +67,7 @@ def return_attrib(obj, attrib, arguments=None):
elif isinstance(obj, types.DictType) or isinstance(obj, types.DictionaryType):
return obj[attrib]
else:
result = reduce(getattr, attrib.split(u'.'), obj)
result = reduce(getattr, attrib.split('.'), obj)
if isinstance(result, types.MethodType):
if arguments:
return result(**arguments)
@@ -86,8 +86,8 @@ def return_attrib(obj, attrib, arguments=None):
# http://snippets.dzone.com/user/jakob
def pretty_size(size, suffixes=None):
suffixes = suffixes or [
(u'B', 1024L), (u'K', 1048576L), (u'M', 1073741824L),
(u'G', 1099511627776L), (u'T', 1125899906842624L)
('B', 1024L), ('K', 1048576L), ('M', 1073741824L),
('G', 1099511627776L), ('T', 1125899906842624L)
]
for suf, lim in suffixes:
@@ -104,20 +104,20 @@ def pretty_size_10(size):
return pretty_size(
size,
suffixes=[
(u'B', 1000L), (u'K', 1000000L), (u'M', 1000000000L),
(u'G', 1000000000000L), (u'T', 1000000000000000L)
('B', 1000L), ('K', 1000000L), ('M', 1000000000L),
('G', 1000000000000L), ('T', 1000000000000000L)
])
def return_type(value):
if isinstance(value, types.FunctionType):
return value.__doc__ if value.__doc__ else _(u'Function found')
return value.__doc__ if value.__doc__ else _('Function found')
elif isinstance(value, types.ClassType):
return u'%s.%s' % (value.__class__.__module__, value.__class__.__name__)
return '%s.%s' % (value.__class__.__module__, value.__class__.__name__)
elif isinstance(value, types.TypeType):
return u'%s.%s' % (value.__module__, value.__name__)
return '%s.%s' % (value.__module__, value.__name__)
elif isinstance(value, types.DictType) or isinstance(value, types.DictionaryType):
return u', '.join(list(value))
return ', '.join(list(value))
else:
return value
@@ -125,8 +125,8 @@ def return_type(value):
# http://stackoverflow.com/questions/4248399/page-range-for-printing-algorithm
def parse_range(astr):
result = set()
for part in astr.split(u','):
x = part.split(u'-')
for part in astr.split(','):
x = part.split('-')
result.update(range(int(x[0]), int(x[-1]) + 1))
return sorted(result)
@@ -140,10 +140,10 @@ def generate_choices_w_labels(choices, display_object_type=True):
label = choice.get_full_name() if choice.get_full_name() else choice
if display_object_type:
verbose_name = unicode(getattr(choice._meta, u'verbose_name', ct.name))
results.append((u'%s,%s' % (ct.model, choice.pk), u'%s: %s' % (verbose_name, label)))
verbose_name = unicode(getattr(choice._meta, 'verbose_name', ct.name))
results.append(('%s,%s' % (ct.model, choice.pk), '%s: %s' % (verbose_name, label)))
else:
results.append((u'%s,%s' % (ct.model, choice.pk), u'%s' % (label)))
results.append(('%s,%s' % (ct.model, choice.pk), '%s' % (label)))
# Sort results by the label not the key value
return sorted(results, key=lambda x: x[1])
@@ -162,9 +162,9 @@ def get_object_name(obj, display_object_type=True):
except AttributeError:
verbose_name = ct_label
return u'%s: %s' % (verbose_name, label)
return '%s: %s' % (verbose_name, label)
else:
return u'%s' % (label)
return '%s' % (label)
def validate_path(path):

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from json import dumps, loads
@@ -39,15 +39,15 @@ def multi_object_action_view(request):
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', reverse('main:home'))))
action = request.GET.get('action', None)
id_list = u','.join([key[3:] for key in request.GET.keys() if key.startswith('pk_')])
id_list = ','.join([key[3:] for key in request.GET.keys() if key.startswith('pk_')])
items_property_list = [loads(key[11:]) for key in request.GET.keys() if key.startswith('properties_')]
if not action:
messages.error(request, _(u'No action selected.'))
messages.error(request, _('No action selected.'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('main:home')))
if not id_list and not items_property_list:
messages.error(request, _(u'Must select at least one item.'))
messages.error(request, _('Must select at least one item.'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('main:home')))
# Separate redirects to keep backwards compatibility with older
@@ -65,17 +65,17 @@ def multi_object_action_view(request):
def get_obj_from_content_type_string(string):
model, pk = string.split(u',')
model, pk = string.split(',')
ct = ContentType.objects.get(model=model)
return ct.get_object_for_this_type(pk=pk)
def assign_remove(request, left_list, right_list, add_method, remove_method, left_list_title=None, right_list_title=None, decode_content_type=False, extra_context=None, grouped=False):
left_list_name = u'left_list'
right_list_name = u'right_list'
left_list_name = 'left_list'
right_list_name = 'right_list'
if request.method == 'POST':
if u'%s-submit' % left_list_name in request.POST.keys():
if '%s-submit' % left_list_name in request.POST.keys():
unselected_list = ChoiceForm(request.POST,
prefix=left_list_name,
choices=left_list())
@@ -99,10 +99,10 @@ def assign_remove(request, left_list, right_list, add_method, remove_method, lef
if settings.DEBUG:
raise
else:
messages.error(request, _(u'Unable to remove %(selection)s.') % {
messages.error(request, _('Unable to remove %(selection)s.') % {
'selection': label, 'right_list_title': right_list_title})
elif u'%s-submit' % right_list_name in request.POST.keys():
elif '%s-submit' % right_list_name in request.POST.keys():
selected_list = ChoiceForm(request.POST,
prefix=right_list_name,
choices=right_list())
@@ -124,7 +124,7 @@ def assign_remove(request, left_list, right_list, add_method, remove_method, lef
if settings.DEBUG:
raise
else:
messages.error(request, _(u'Unable to add %(selection)s.') % {
messages.error(request, _('Unable to add %(selection)s.') % {
'selection': label, 'right_list_title': right_list_title})
unselected_list = ChoiceForm(prefix=left_list_name, choices=left_list())
selected_list = ChoiceForm(prefix=right_list_name, choices=right_list())
@@ -137,7 +137,7 @@ def assign_remove(request, left_list, right_list, add_method, remove_method, lef
'context': {
'form': unselected_list,
'title': left_list_title or ' ',
'submit_label': _(u'Add'),
'submit_label': _('Add'),
'submit_icon_famfam': 'add'
}
},
@@ -148,7 +148,7 @@ def assign_remove(request, left_list, right_list, add_method, remove_method, lef
'context': {
'form': selected_list,
'title': right_list_title or ' ',
'submit_label': _(u'Remove'),
'submit_label': _('Remove'),
'submit_icon_famfam': 'delete'
}
},
@@ -171,7 +171,7 @@ def current_user_details(request):
return render_to_response(
'main/generic_form.html', {
'form': form,
'title': _(u'Current user details'),
'title': _('Current user details'),
'read_only': True,
},
context_instance=RequestContext(request))
@@ -186,7 +186,7 @@ def current_user_locale_profile_details(request):
return render_to_response(
'main/generic_form.html', {
'form': form,
'title': _(u'Current user locale profile details'),
'title': _('Current user locale profile details'),
'read_only': True,
},
context_instance=RequestContext(request))
@@ -203,10 +203,10 @@ def current_user_edit(request):
form = UserForm(instance=request.user, data=request.POST)
if form.is_valid():
if User.objects.filter(email=form.cleaned_data['email']).exclude(pk=request.user.pk).count():
messages.error(request, _(u'E-mail conflict, another user has that same email.'))
messages.error(request, _('E-mail conflict, another user has that same email.'))
else:
form.save()
messages.success(request, _(u'Current user\'s details updated.'))
messages.success(request, _('Current user\'s details updated.'))
return HttpResponseRedirect(next)
else:
form = UserForm(instance=request.user)
@@ -215,7 +215,7 @@ def current_user_edit(request):
'main/generic_form.html', {
'form': form,
'next': next,
'title': _(u'Edit current user details'),
'title': _('Edit current user details'),
},
context_instance=RequestContext(request))
@@ -238,7 +238,7 @@ def current_user_locale_profile_edit(request):
else:
request.set_cookie(settings.LANGUAGE_COOKIE_NAME, form.cleaned_data['language'])
messages.success(request, _(u'Current user\'s locale profile details updated.'))
messages.success(request, _('Current user\'s locale profile details updated.'))
return HttpResponseRedirect(next)
else:
form = LocaleProfileForm(instance=request.user.locale_profile)
@@ -247,7 +247,7 @@ def current_user_locale_profile_edit(request):
'main/generic_form.html', {
'form': form,
'next': next,
'title': _(u'Edit current user locale profile details'),
'title': _('Edit current user locale profile details'),
},
context_instance=RequestContext(request))
@@ -278,7 +278,7 @@ def license_view(request):
return render_to_response(
'main/generic_detail.html', {
'form': form,
'title': _(u'License'),
'title': _('License'),
},
context_instance=RequestContext(request))
@@ -287,7 +287,7 @@ def password_change_view(request):
"""
Password change wrapper for better control
"""
context = {'title': _(u'Current user password change')}
context = {'title': _('Current user password change')}
return password_change(
request,
@@ -302,7 +302,7 @@ def password_change_done(request):
View called when the new user password has been accepted
"""
messages.success(request, _(u'Your password has been successfully changed.'))
messages.success(request, _('Your password has been successfully changed.'))
return redirect('common:current_user_details')

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from itertools import chain
import os
@@ -15,7 +17,7 @@ class PlainWidget(forms.widgets.Widget):
widget and reduces the output to only it's value
"""
def render(self, name, value, attrs=None):
return mark_safe(u'%s' % value)
return mark_safe('%s' % value)
class DetailSelectMultiple(forms.widgets.SelectMultiple):
@@ -28,7 +30,7 @@ class DetailSelectMultiple(forms.widgets.SelectMultiple):
value = ''
final_attrs = self.build_attrs(attrs, name=name)
css_class = final_attrs.get('class', 'list')
output = u'<ul class="%s">' % css_class
output = '<ul class="%s">' % css_class
options = None
if value:
if getattr(value, '__iter__', None):
@@ -39,7 +41,7 @@ class DetailSelectMultiple(forms.widgets.SelectMultiple):
self.choices if index == value]
else:
if self.choices:
if self.choices[0] != (u'', u'---------') and value != []:
if self.choices[0] != ('', '---------') and value != []:
options = [(index, string) for index, string in
self.choices]
@@ -47,16 +49,16 @@ class DetailSelectMultiple(forms.widgets.SelectMultiple):
for index, string in options:
if self.queryset:
try:
output += u'<li><a href="%s">%s</a></li>' % (
output += '<li><a href="%s">%s</a></li>' % (
self.queryset.get(pk=index).get_absolute_url(),
string)
except AttributeError:
output += u'<li>%s</li>' % (string)
output += '<li>%s</li>' % (string)
else:
output += u'<li>%s</li>' % string
output += '<li>%s</li>' % string
else:
output += u'<li>%s</li>' % _(u'None')
return mark_safe(output + u'</ul>\n')
output += '<li>%s</li>' % _('None')
return mark_safe(output + '</ul>\n')
def exists_with_famfam(path):
@@ -66,11 +68,11 @@ def exists_with_famfam(path):
return exception
def two_state_template(state, famfam_ok_icon=u'tick', famfam_fail_icon=u'cross'):
def two_state_template(state, famfam_ok_icon='tick', famfam_fail_icon='cross'):
if state:
return mark_safe(u'<span class="famfam active famfam-%s"></span>' % famfam_ok_icon)
return mark_safe('<span class="famfam active famfam-%s"></span>' % famfam_ok_icon)
else:
return mark_safe(u'<span class="famfam active famfam-%s"></span>' % famfam_fail_icon)
return mark_safe('<span class="famfam active famfam-%s"></span>' % famfam_fail_icon)
class TextAreaDiv(forms.widgets.Widget):
@@ -88,11 +90,11 @@ class TextAreaDiv(forms.widgets.Widget):
def render(self, name, value, attrs=None):
if value is None:
value = u''
value = ''
flat_attrs = flatatt(self.build_attrs(attrs, name=name))
content = conditional_escape(force_unicode(value))
result = u'<pre%s>%s</pre>' % (flat_attrs, content)
result = '<pre%s>%s</pre>' % (flat_attrs, content)
return mark_safe(result)
@@ -124,7 +126,7 @@ class ScrollableCheckboxSelectMultiple(forms.widgets.CheckboxSelectMultiple):
value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul class="undecorated_list" style="margin-left: 5px; margin-top: 3px; margin-bottom: 3px;">']
output = ['<ul class="undecorated_list" style="margin-left: 5px; margin-top: 3px; margin-bottom: 3px;">']
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
@@ -132,7 +134,7 @@ class ScrollableCheckboxSelectMultiple(forms.widgets.CheckboxSelectMultiple):
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
label_for = ' for="%s"' % final_attrs['id']
else:
label_for = ''
@@ -140,7 +142,7 @@ class ScrollableCheckboxSelectMultiple(forms.widgets.CheckboxSelectMultiple):
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
output.append(u'</ul>')
output.append('<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
output.append('</ul>')
return mark_safe(u'<div class="text_area_div">%s</div>' % u'\n'.join(output))
return mark_safe('<div class="text_area_div">%s</div>' % '\n'.join(output))

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import hashlib
import logging
@@ -31,7 +31,7 @@ def cache_cleanup(input_filepath, *args, **kwargs):
def create_image_cache_filename(input_filepath, *args, **kwargs):
if input_filepath:
hash_value = HASH_FUNCTION(u''.join([HASH_FUNCTION(smart_str(input_filepath)), unicode(args), unicode(kwargs)]))
hash_value = HASH_FUNCTION(''.join([HASH_FUNCTION(smart_str(input_filepath)), unicode(args), unicode(kwargs)]))
return os.path.join(TEMPORARY_DIRECTORY, hash_value)
else:
return None
@@ -71,7 +71,7 @@ def convert(input_filepath, output_filepath=None, cleanup_files=False, mimetype=
transformations.append(
{
'transformation': TRANSFORMATION_RESIZE,
'arguments': dict(zip([u'width', u'height'], size.split(DIMENSION_SEPARATOR)))
'arguments': dict(zip(['width', 'height'], size.split(DIMENSION_SEPARATOR)))
}
)

View File

@@ -1,18 +1,21 @@
from __future__ import unicode_literals
class ConverterBase(object):
"""
Base class that all backend classes must inherit
"""
def convert_file(self, input_filepath, *args, **kwargs):
raise NotImplementedError("Your %s class has not defined a convert_file() method, which is required." % self.__class__.__name__)
raise NotImplementedError('Your %s class has not defined a convert_file() method, which is required.' % self.__class__.__name__)
def convert_document(self, document, *args, **kwargs):
raise NotImplementedError("Your %s class has not defined a convert_document() method, which is required." % self.__class__.__name__)
raise NotImplementedError('Your %s class has not defined a convert_document() method, which is required.' % self.__class__.__name__)
def get_format_list(self):
raise NotImplementedError("Your %s class has not defined a get_format_list() method, which is required." % self.__class__.__name__)
raise NotImplementedError('Your %s class has not defined a get_format_list() method, which is required.' % self.__class__.__name__)
def get_available_transformations(self):
raise NotImplementedError("Your %s class has not defined a get_available_transformations() method, which is required." % self.__class__.__name__)
raise NotImplementedError('Your %s class has not defined a get_available_transformations() method, which is required.' % self.__class__.__name__)
def get_page_count(self, input_filepath):
raise NotImplementedError("Your %s class has not defined a get_page_count() method, which is required." % self.__class__.__name__)
raise NotImplementedError('Your %s class has not defined a get_page_count() method, which is required.' % self.__class__.__name__)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import subprocess
@@ -10,15 +10,15 @@ from ..literals import (DEFAULT_FILE_FORMAT, DEFAULT_PAGE_NUMBER,
DIMENSION_SEPARATOR)
from ..settings import GM_PATH, GM_SETTINGS
CONVERTER_ERROR_STARTS_WITH = u'starts with'
CONVERTER_ERROR_STRING_NO_DECODER = u'No decode delegate for this image format'
CONVERTER_ERROR_STARTS_WITH = 'starts with'
CONVERTER_ERROR_STRING_NO_DECODER = 'No decode delegate for this image format'
class GraphicsMagick(ConverterBase):
def identify_file(self, input_filepath, arguments=None):
command = []
command.append(unicode(GM_PATH))
command.append(u'identify')
command.append('identify')
if arguments:
command.extend(arguments)
command.append(unicode(input_filepath))
@@ -39,32 +39,32 @@ class GraphicsMagick(ConverterBase):
dimensions.append(unicode(transformation['arguments']['width']))
if 'height' in transformation['arguments']:
dimensions.append(unicode(transformation['arguments']['height']))
arguments.append(u'-resize')
arguments.append(u'%s' % DIMENSION_SEPARATOR.join(dimensions))
arguments.append('-resize')
arguments.append('%s' % DIMENSION_SEPARATOR.join(dimensions))
elif transformation['transformation'] == TRANSFORMATION_ZOOM:
arguments.append(u'-resize')
arguments.append(u'%d%%' % transformation['arguments']['percent'])
arguments.append('-resize')
arguments.append('%d%%' % transformation['arguments']['percent'])
elif transformation['transformation'] == TRANSFORMATION_ROTATE:
arguments.append(u'-rotate')
arguments.append(u'%s' % transformation['arguments']['degrees'])
arguments.append('-rotate')
arguments.append('%s' % transformation['arguments']['degrees'])
except:
pass
if file_format.lower() == u'jpeg' or file_format.lower() == u'jpg':
arguments.append(u'-quality')
arguments.append(u'85')
if file_format.lower() == 'jpeg' or file_format.lower() == 'jpg':
arguments.append('-quality')
arguments.append('85')
# Graphicsmagick page number is 0 base
input_arg = u'%s[%d]' % (input_filepath, page - 1)
input_arg = '%s[%d]' % (input_filepath, page - 1)
# Specify the file format next to the output filename
output_filepath = u'%s:%s' % (file_format, output_filepath)
output_filepath = '%s:%s' % (file_format, output_filepath)
command = []
command.append(unicode(GM_PATH))
command.append(u'convert')
command.append('convert')
command.extend(unicode(GM_SETTINGS).split())
command.append(unicode(input_arg))
if arguments:

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import subprocess
@@ -9,7 +9,7 @@ from ..literals import (DEFAULT_FILE_FORMAT, DEFAULT_PAGE_NUMBER,
TRANSFORMATION_ROTATE, TRANSFORMATION_ZOOM)
from ..settings import IM_CONVERT_PATH, IM_IDENTIFY_PATH
CONVERTER_ERROR_STRING_NO_DECODER = u'no decode delegate for this image format'
CONVERTER_ERROR_STRING_NO_DECODER = 'no decode delegate for this image format'
class ImageMagick(ConverterBase):
@@ -36,28 +36,28 @@ class ImageMagick(ConverterBase):
dimensions.append(unicode(transformation['arguments']['width']))
if 'height' in transformation['arguments']:
dimensions.append(unicode(transformation['arguments']['height']))
arguments.append(u'-resize')
arguments.append(u'%s' % DIMENSION_SEPARATOR.join(dimensions))
arguments.append('-resize')
arguments.append('%s' % DIMENSION_SEPARATOR.join(dimensions))
elif transformation['transformation'] == TRANSFORMATION_ZOOM:
arguments.append(u'-resize')
arguments.append(u'%d%%' % transformation['arguments']['percent'])
arguments.append('-resize')
arguments.append('%d%%' % transformation['arguments']['percent'])
elif transformation['transformation'] == TRANSFORMATION_ROTATE:
arguments.append(u'-rotate')
arguments.append(u'%s' % transformation['arguments']['degrees'])
arguments.append('-rotate')
arguments.append('%s' % transformation['arguments']['degrees'])
except:
pass
if file_format.lower() == u'jpeg' or file_format.lower() == u'jpg':
arguments.append(u'-quality')
arguments.append(u'85')
if file_format.lower() == 'jpeg' or file_format.lower() == 'jpg':
arguments.append('-quality')
arguments.append('85')
# Imagemagick page number is 0 base
input_arg = u'%s[%d]' % (input_filepath, page - 1)
input_arg = '%s[%d]' % (input_filepath, page - 1)
# Specify the file format next to the output filename
output_filepath = u'%s:%s' % (file_format, output_filepath)
output_filepath = '%s:%s' % (file_format, output_filepath)
command = []
command.append(unicode(IM_CONVERT_PATH))

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import logging

View File

@@ -1,3 +1,6 @@
from __future__ import unicode_literals
class ConvertError(Exception):
"""
Base exception for all coverter app exceptions

View File

@@ -1,48 +1,50 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
DEFAULT_ZOOM_LEVEL = 100
DEFAULT_ROTATION = 0
DEFAULT_PAGE_NUMBER = 1
DEFAULT_FILE_FORMAT = u'jpeg'
DEFAULT_FILE_FORMAT_MIMETYPE = u'image/jpeg'
DEFAULT_FILE_FORMAT = 'jpeg'
DEFAULT_FILE_FORMAT_MIMETYPE = 'image/jpeg'
DIMENSION_SEPARATOR = u'x'
DIMENSION_SEPARATOR = 'x'
TRANSFORMATION_RESIZE = u'resize'
TRANSFORMATION_ROTATE = u'rotate'
TRANSFORMATION_DENSITY = u'density'
TRANSFORMATION_ZOOM = u'zoom'
TRANSFORMATION_RESIZE = 'resize'
TRANSFORMATION_ROTATE = 'rotate'
TRANSFORMATION_DENSITY = 'density'
TRANSFORMATION_ZOOM = 'zoom'
TRANSFORMATION_CHOICES = {
TRANSFORMATION_RESIZE: {
'label': _(u'Resize'),
'description': _(u'Resize.'),
'label': _('Resize'),
'description': _('Resize.'),
'arguments': [
{'name': 'width', 'label': _(u'Width'), 'required': True},
{'name': 'height', 'label': _(u'Height'), 'required': False},
{'name': 'width', 'label': _('Width'), 'required': True},
{'name': 'height', 'label': _('Height'), 'required': False},
]
},
TRANSFORMATION_ROTATE: {
'label': _(u'Rotate'),
'description': _(u'Rotate by n degress.'),
'label': _('Rotate'),
'description': _('Rotate by n degress.'),
'arguments': [
{'name': 'degrees', 'label': _(u'Degrees'), 'required': True}
{'name': 'degrees', 'label': _('Degrees'), 'required': True}
]
},
TRANSFORMATION_DENSITY: {
'label': _(u'Density'),
'description': _(u'Change the resolution (ie: DPI) without resizing.'),
'label': _('Density'),
'description': _('Change the resolution (ie: DPI) without resizing.'),
'arguments': [
{'name': 'width', 'label': _(u'Width'), 'required': True},
{'name': 'height', 'label': _(u'Height'), 'required': False},
{'name': 'width', 'label': _('Width'), 'required': True},
{'name': 'height', 'label': _('Height'), 'required': False},
]
},
TRANSFORMATION_ZOOM: {
'label': _(u'Zoom'),
'description': _(u'Zoom by n percent.'),
'label': _('Zoom'),
'description': _('Zoom by n percent.'),
'arguments': [
{'name': 'percent', 'label': _(u'Percent'), 'required': True}
{'name': 'percent', 'label': _('Percent'), 'required': True}
]
},
}

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import os
@@ -10,53 +10,53 @@ from mimetype.api import get_mimetype
from .exceptions import OfficeBackendError, UnknownFileFormat
from .settings import LIBREOFFICE_PATH
CACHED_FILE_SUFFIX = u'_office_converter'
CACHED_FILE_SUFFIX = '_office_converter'
CONVERTER_OFFICE_FILE_MIMETYPES = [
u'application/msword',
u'application/mswrite',
u'application/mspowerpoint',
u'application/msexcel',
u'application/pgp-keys',
u'application/vnd.ms-excel',
u'application/vnd.ms-excel.addin.macroEnabled.12',
u'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
u'application/vnd.ms-powerpoint',
u'application/vnd.oasis.opendocument.chart',
u'application/vnd.oasis.opendocument.chart-template',
u'application/vnd.oasis.opendocument.formula',
u'application/vnd.oasis.opendocument.formula-template',
u'application/vnd.oasis.opendocument.graphics',
u'application/vnd.oasis.opendocument.graphics-template',
u'application/vnd.oasis.opendocument.image',
u'application/vnd.oasis.opendocument.image-template',
u'application/vnd.oasis.opendocument.presentation',
u'application/vnd.oasis.opendocument.presentation-template',
u'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
u'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
u'application/vnd.openxmlformats-officedocument.presentationml.template',
u'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
u'application/vnd.openxmlformats-officedocument.presentationml.presentation',
u'application/vnd.openxmlformats-officedocument.presentationml.slide',
u'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
u'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
u'application/vnd.oasis.opendocument.spreadsheet',
u'application/vnd.oasis.opendocument.spreadsheet-template',
u'application/vnd.oasis.opendocument.text',
u'application/vnd.oasis.opendocument.text-master',
u'application/vnd.oasis.opendocument.text-template',
u'application/vnd.oasis.opendocument.text-web',
u'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
u'application/vnd.ms-office',
u'application/xml',
u'text/x-c',
u'text/x-c++',
u'text/x-pascal',
u'text/x-msdos-batch',
u'text/x-python',
u'text/x-shellscript',
u'text/plain',
u'text/rtf',
'application/msword',
'application/mswrite',
'application/mspowerpoint',
'application/msexcel',
'application/pgp-keys',
'application/vnd.ms-excel',
'application/vnd.ms-excel.addin.macroEnabled.12',
'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'application/vnd.ms-powerpoint',
'application/vnd.oasis.opendocument.chart',
'application/vnd.oasis.opendocument.chart-template',
'application/vnd.oasis.opendocument.formula',
'application/vnd.oasis.opendocument.formula-template',
'application/vnd.oasis.opendocument.graphics',
'application/vnd.oasis.opendocument.graphics-template',
'application/vnd.oasis.opendocument.image',
'application/vnd.oasis.opendocument.image-template',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.presentation-template',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'application/vnd.openxmlformats-officedocument.presentationml.template',
'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml.slide',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.spreadsheet-template',
'application/vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.text-master',
'application/vnd.oasis.opendocument.text-template',
'application/vnd.oasis.opendocument.text-web',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-office',
'application/xml',
'text/x-c',
'text/x-c++',
'text/x-pascal',
'text/x-msdos-batch',
'text/x-python',
'text/x-shellscript',
'text/plain',
'text/rtf',
]
logger = logging.getLogger(__name__)
@@ -88,7 +88,7 @@ class OfficeConverter(object):
if self.mimetype in CONVERTER_OFFICE_FILE_MIMETYPES:
# Cache results of conversion
self.output_filepath = os.path.join(TEMPORARY_DIRECTORY, u''.join([self.input_filepath, CACHED_FILE_SUFFIX]))
self.output_filepath = os.path.join(TEMPORARY_DIRECTORY, ''.join([self.input_filepath, CACHED_FILE_SUFFIX]))
self.exists = os.path.exists(self.output_filepath)
if not self.exists:
try:
@@ -122,11 +122,11 @@ class OfficeConverterBackendDirect(object):
command = []
command.append(self.libreoffice_path)
command.append(u'--headless')
command.append(u'--convert-to')
command.append(u'pdf')
command.append('--headless')
command.append('--convert-to')
command.append('pdf')
command.append(self.input_filepath)
command.append(u'--outdir')
command.append('--outdir')
command.append(TEMPORARY_DIRECTORY)
logger.debug('command: %s', command)

View File

@@ -1,19 +1,19 @@
"""Configuration options for the converter app"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from smart_settings.api import register_settings
register_settings(
namespace=u'converter',
module=u'converter.settings',
namespace='converter',
module='converter.settings',
settings=[
{'name': u'IM_CONVERT_PATH', 'global_name': u'CONVERTER_IM_CONVERT_PATH', 'default': u'/usr/bin/convert', 'description': _(u'File path to imagemagick\'s convert program.'), 'exists': True},
{'name': u'IM_IDENTIFY_PATH', 'global_name': u'CONVERTER_IM_IDENTIFY_PATH', 'default': u'/usr/bin/identify', 'description': _(u'File path to imagemagick\'s identify program.'), 'exists': True},
{'name': u'GM_PATH', 'global_name': u'CONVERTER_GM_PATH', 'default': u'/usr/bin/gm', 'description': _(u'File path to graphicsmagick\'s program.'), 'exists': True},
{'name': u'GM_SETTINGS', 'global_name': u'CONVERTER_GM_SETTINGS', 'default': u''},
{'name': u'GRAPHICS_BACKEND', 'global_name': u'CONVERTER_GRAPHICS_BACKEND', 'default': u'converter.backends.python.Python', 'description': _(u'Graphics conversion backend to use. Options are: converter.backends.imagemagick.ImageMagick, converter.backends.graphicsmagick.GraphicsMagick and converter.backends.python.Python')},
{'name': u'LIBREOFFICE_PATH', 'global_name': u'CONVERTER_LIBREOFFICE_PATH', 'default': u'/usr/bin/libreoffice', 'exists': True, 'description': _(u'Path to the libreoffice program.')},
{'name': u'PDFTOPPM_PATH', 'global_name': u'CONVERTER_PDFTOPPM_PATH', 'default': u'/usr/bin/pdftoppm', 'exists': True, 'description': _(u'Path to the Popple program pdftoppm.')},
{'name': 'IM_CONVERT_PATH', 'global_name': 'CONVERTER_IM_CONVERT_PATH', 'default': '/usr/bin/convert', 'description': _('File path to imagemagick\'s convert program.'), 'exists': True},
{'name': 'IM_IDENTIFY_PATH', 'global_name': 'CONVERTER_IM_IDENTIFY_PATH', 'default': '/usr/bin/identify', 'description': _('File path to imagemagick\'s identify program.'), 'exists': True},
{'name': 'GM_PATH', 'global_name': 'CONVERTER_GM_PATH', 'default': '/usr/bin/gm', 'description': _('File path to graphicsmagick\'s program.'), 'exists': True},
{'name': 'GM_SETTINGS', 'global_name': 'CONVERTER_GM_SETTINGS', 'default': ''},
{'name': 'GRAPHICS_BACKEND', 'global_name': 'CONVERTER_GRAPHICS_BACKEND', 'default': 'converter.backends.python.Python', 'description': _('Graphics conversion backend to use. Options are: converter.backends.imagemagick.ImageMagick, converter.backends.graphicsmagick.GraphicsMagick and converter.backends.python.Python')},
{'name': 'LIBREOFFICE_PATH', 'global_name': 'CONVERTER_LIBREOFFICE_PATH', 'default': '/usr/bin/libreoffice', 'exists': True, 'description': _('Path to the libreoffice program.')},
{'name': 'PDFTOPPM_PATH', 'global_name': 'CONVERTER_PDFTOPPM_PATH', 'default': '/usr/bin/pdftoppm', 'exists': True, 'description': _('Path to the Popple program pdftoppm.')},
]
)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from hkp import Key as KeyServerKey

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import os
@@ -37,7 +37,7 @@ class Key(object):
if exclude:
excluded_id = exclude.key_id
else:
excluded_id = u''
excluded_id = ''
for key in keys:
if not key['keyid'] in excluded_id:
key_instance = Key(
@@ -89,10 +89,10 @@ class Key(object):
@property
def user_ids(self):
return u', '.join(self.uids)
return ', '.join(self.uids)
def __str__(self):
return '%s "%s" (%s)' % (self.key_id, self.user_ids, KEY_TYPES.get(self.type, _(u'Unknown')))
return '%s "%s" (%s)' % (self.key_id, self.user_ids, KEY_TYPES.get(self.type, _('Unknown')))
def __unicode__(self):
return unicode(self.__str__())
@@ -129,7 +129,7 @@ class GPG(object):
try:
self.gpg = gnupg.GPG(**kwargs)
except Exception as exception:
raise GPGException(u'ERROR: GPG initialization error; %s' % exception)
raise GPGException('ERROR: GPG initialization error; %s' % exception)
def verify_file(self, file_input, detached_signature=None, fetch_key=False):
"""
@@ -242,7 +242,7 @@ class GPG(object):
return result
def create_key(self, *args, **kwargs):
if kwargs.get('passphrase') == u'':
if kwargs.get('passphrase') == '':
kwargs.pop('passphrase')
input_data = self.gpg.gen_key_input(**kwargs)
@@ -271,7 +271,7 @@ class GPG(object):
def query(self, term):
results = {}
for keyserver in self.keyservers:
url = u'http://%s' % keyserver
url = 'http://%s' % keyserver
server = KeyServer(url)
try:
key_list = server.search(term)

View File

@@ -1,9 +1,11 @@
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
class KeySearchForm(forms.Form):
term = forms.CharField(
label=_(u'Term'),
help_text=_(u'Name, e-mail, key ID or key fingerprint to look for.')
label=_('Term'),
help_text=_('Name, e-mail, key ID or key fingerprint to look for.')
)

View File

@@ -1,11 +1,15 @@
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from .permissions import (PERMISSION_KEY_DELETE, PERMISSION_KEY_RECEIVE,
PERMISSION_KEY_VIEW, PERMISSION_KEYSERVER_QUERY)
from .permissions import (
PERMISSION_KEY_DELETE, PERMISSION_KEY_RECEIVE, PERMISSION_KEY_VIEW,
PERMISSION_KEYSERVER_QUERY
)
private_keys = {'text': _(u'Private keys'), 'view': 'django_gpg:key_private_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}
public_keys = {'text': _(u'Public keys'), 'view': 'django_gpg:key_public_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}
key_delete = {'text': _(u'Delete'), 'view': 'django_gpg:key_delete', 'args': ['object.fingerprint', 'object.type'], 'famfam': 'key_delete', 'permissions': [PERMISSION_KEY_DELETE]}
key_query = {'text': _(u'Query keyservers'), 'view': 'django_gpg:key_query', 'famfam': 'zoom', 'permissions': [PERMISSION_KEYSERVER_QUERY]}
key_receive = {'text': _(u'Import'), 'view': 'django_gpg:key_receive', 'args': 'object.keyid', 'famfam': 'key_add', 'keep_query': True, 'permissions': [PERMISSION_KEY_RECEIVE]}
key_setup = {'text': _(u'Key management'), 'view': 'django_gpg:key_public_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}
private_keys = {'text': _('Private keys'), 'view': 'django_gpg:key_private_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}
public_keys = {'text': _('Public keys'), 'view': 'django_gpg:key_public_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}
key_delete = {'text': _('Delete'), 'view': 'django_gpg:key_delete', 'args': ['object.fingerprint', 'object.type'], 'famfam': 'key_delete', 'permissions': [PERMISSION_KEY_DELETE]}
key_query = {'text': _('Query keyservers'), 'view': 'django_gpg:key_query', 'famfam': 'zoom', 'permissions': [PERMISSION_KEYSERVER_QUERY]}
key_receive = {'text': _('Import'), 'view': 'django_gpg:key_receive', 'args': 'object.keyid', 'famfam': 'key_add', 'keep_query': True, 'permissions': [PERMISSION_KEY_RECEIVE]}
key_setup = {'text': _('Key management'), 'view': 'django_gpg:key_public_list', 'args': 'object.pk', 'famfam': 'key', 'icon': 'key.png', 'permissions': [PERMISSION_KEY_VIEW]}

View File

@@ -1,12 +1,12 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
django_gpg_namespace = PermissionNamespace('django_gpg', _(u'Key management'))
django_gpg_namespace = PermissionNamespace('django_gpg', _('Key management'))
PERMISSION_KEY_VIEW = Permission.objects.register(django_gpg_namespace, 'key_view', _(u'View keys'))
PERMISSION_KEY_DELETE = Permission.objects.register(django_gpg_namespace, 'key_delete', _(u'Delete keys'))
PERMISSION_KEYSERVER_QUERY = Permission.objects.register(django_gpg_namespace, 'keyserver_query', _(u'Query keyservers'))
PERMISSION_KEY_RECEIVE = Permission.objects.register(django_gpg_namespace, 'key_receive', _(u'Import keys from keyservers'))
PERMISSION_KEY_VIEW = Permission.objects.register(django_gpg_namespace, 'key_view', _('View keys'))
PERMISSION_KEY_DELETE = Permission.objects.register(django_gpg_namespace, 'key_delete', _('Delete keys'))
PERMISSION_KEYSERVER_QUERY = Permission.objects.register(django_gpg_namespace, 'keyserver_query', _('Query keyservers'))
PERMISSION_KEY_RECEIVE = Permission.objects.register(django_gpg_namespace, 'key_receive', _('Import keys from keyservers'))

View File

@@ -1,19 +1,18 @@
"""
Configuration options for the django_gpg app
"""
from __future__ import unicode_literals
import os
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from smart_settings.api import register_settings
register_settings(
namespace=u'django_gpg',
module=u'django_gpg.settings',
namespace='django_gpg',
module='django_gpg.settings',
settings=[
{'name': u'KEYSERVERS', 'global_name': u'SIGNATURES_KEYSERVERS', 'default': ['pool.sks-keyservers.net'], 'description': _(u'List of keyservers to be queried for unknown keys.')},
{'name': u'GPG_HOME', 'global_name': u'SIGNATURES_GPG_HOME', 'default': os.path.join(settings.MEDIA_ROOT, u'gpg_home'), 'description': _(u'Home directory used to store keys as well as configuration files.')},
{'name': u'GPG_PATH', 'global_name': u'SIGNATURES_GPG_PATH', 'default': u'/usr/bin/gpg', 'description': _(u'Path to the GPG binary.')},
{'name': 'KEYSERVERS', 'global_name': 'SIGNATURES_KEYSERVERS', 'default': ['pool.sks-keyservers.net'], 'description': _('List of keyservers to be queried for unknown keys.')},
{'name': 'GPG_HOME', 'global_name': 'SIGNATURES_GPG_HOME', 'default': os.path.join(settings.MEDIA_ROOT, 'gpg_home'), 'description': _('Home directory used to store keys as well as configuration files.')},
{'name': 'GPG_PATH', 'global_name': 'SIGNATURES_GPG_PATH', 'default': '/usr/bin/gpg', 'description': _('Path to the GPG binary.')},
]
)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
import logging
@@ -15,8 +15,10 @@ from permissions.models import Permission
from .api import Key
from .exceptions import KeyImportError
from .forms import KeySearchForm
from .permissions import (PERMISSION_KEY_DELETE, PERMISSION_KEY_RECEIVE,
PERMISSION_KEY_VIEW, PERMISSION_KEYSERVER_QUERY)
from .permissions import (
PERMISSION_KEY_DELETE, PERMISSION_KEY_RECEIVE, PERMISSION_KEY_VIEW,
PERMISSION_KEYSERVER_QUERY
)
from .runtime import gpg
logger = logging.getLogger(__name__)
@@ -35,12 +37,12 @@ def key_receive(request, key_id):
results = gpg.query(term)
keys_dict = dict([(key.keyid, key) for key in results])
key = gpg.import_key(keys_dict[key_id].key)
messages.success(request, _(u'Key: %s, imported successfully.') % key)
messages.success(request, _('Key: %s, imported successfully.') % key)
return HttpResponseRedirect(next)
except (KeyImportError, KeyError, TypeError) as exception:
messages.error(
request,
_(u'Unable to import key id: %(key_id)s; %(error)s') %
_('Unable to import key id: %(key_id)s; %(error)s') %
{
'key_id': key_id,
'error': exception,
@@ -49,8 +51,8 @@ def key_receive(request, key_id):
return HttpResponseRedirect(previous)
return render_to_response('main/generic_confirm.html', {
'title': _(u'Import key'),
'message': _(u'Are you sure you wish to import key id: %s?') % key_id,
'title': _('Import key'),
'message': _('Are you sure you wish to import key id: %s?') % key_id,
'next': next,
'previous': previous,
'submit_method': 'GET',
@@ -63,10 +65,10 @@ def key_list(request, secret=True):
if secret:
object_list = Key.get_all(gpg, secret=True)
title = _(u'Private keys')
title = _('Private keys')
else:
object_list = Key.get_all(gpg)
title = _(u'Public keys')
title = _('Public keys')
return render_to_response('main/generic_list.html', {
'object_list': object_list,
@@ -74,12 +76,12 @@ def key_list(request, secret=True):
'hide_object': True,
'extra_columns': [
{
'name': _(u'Key ID'),
'name': _('Key ID'),
'attribute': 'key_id',
},
{
'name': _(u'Owner'),
'attribute': encapsulate(lambda x: u', '.join(x.uids)),
'name': _('Owner'),
'attribute': encapsulate(lambda x: ', '.join(x.uids)),
},
]
}, context_instance=RequestContext(request))
@@ -98,16 +100,16 @@ def key_delete(request, fingerprint, key_type):
if request.method == 'POST':
try:
gpg.delete_key(key)
messages.success(request, _(u'Key: %s, deleted successfully.') % fingerprint)
messages.success(request, _('Key: %s, deleted successfully.') % fingerprint)
return HttpResponseRedirect(next)
except Exception as exception:
messages.error(request, exception)
return HttpResponseRedirect(previous)
return render_to_response('main/generic_confirm.html', {
'title': _(u'Delete key'),
'title': _('Delete key'),
'delete_view': True,
'message': _(u'Are you sure you wish to delete key: %s? If you try to delete a public key that is part of a public/private pair the private key will be deleted as well.') % key,
'message': _('Are you sure you wish to delete key: %s? If you try to delete a public key that is part of a public/private pair the private key will be deleted as well.') % key,
'next': next,
'previous': previous,
}, context_instance=RequestContext(request))
@@ -124,7 +126,7 @@ def key_query(request):
{
'name': 'main/generic_form_subtemplate.html',
'context': {
'title': _(u'Query key server'),
'title': _('Query key server'),
'form': form,
'submit_method': 'GET',
},
@@ -137,46 +139,46 @@ def key_query(request):
{
'name': 'main/generic_list_subtemplate.html',
'context': {
'title': _(u'results'),
'title': _('results'),
'object_list': results,
'hide_object': True,
'extra_columns': [
{
'name': _(u'ID'),
'name': _('ID'),
'attribute': 'keyid',
},
{
'name': _(u'Type'),
'name': _('Type'),
'attribute': 'algo',
},
{
'name': _(u'Creation date'),
'name': _('Creation date'),
'attribute': 'creation_date',
},
{
'name': _(u'Disabled'),
'name': _('Disabled'),
'attribute': 'disabled',
},
{
'name': _(u'Expiration date'),
'name': _('Expiration date'),
'attribute': 'expiration_date',
},
{
'name': _(u'Expired'),
'name': _('Expired'),
'attribute': 'expired',
},
{
'name': _(u'Length'),
'name': _('Length'),
'attribute': 'key_length',
},
{
'name': _(u'Revoked'),
'name': _('Revoked'),
'attribute': 'revoked',
},
{
'name': _(u'Identifies'),
'attribute': encapsulate(lambda x: u', '.join([identity.uid for identity in x.identities])),
'name': _('Identifies'),
'attribute': encapsulate(lambda x: ', '.join([identity.uid for identity in x.identities])),
},
]
},

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from acls.api import class_permissions
from acls.permissions import ACLS_VIEW_ACL, ACLS_EDIT_ACL

View File

@@ -1,7 +1,7 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from acls.permissions import ACLS_VIEW_ACL
acl_list = {'text': _(u'ACLs'), 'view': 'document_acls:document_acl_list', 'args': 'object.pk', 'famfam': 'lock', 'permissions': [ACLS_VIEW_ACL]}
acl_list = {'text': _('ACLs'), 'view': 'document_acls:document_acl_list', 'args': 'object.pk', 'famfam': 'lock', 'permissions': [ACLS_VIEW_ACL]}

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns('document_acls.views',

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404
from acls.views import acl_list_for

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.contrib.comments.models import Comment
from django.contrib.contenttypes import generic
@@ -11,8 +11,10 @@ from documents.models import Document
from navigation.api import register_links, register_model_list_columns
from .links import comment_add, comment_delete, comments_for_document
from .permissions import (PERMISSION_COMMENT_CREATE,
PERMISSION_COMMENT_DELETE, PERMISSION_COMMENT_VIEW)
from .permissions import (
PERMISSION_COMMENT_CREATE, PERMISSION_COMMENT_DELETE,
PERMISSION_COMMENT_VIEW
)
Document.add_to_class(
@@ -30,15 +32,15 @@ class_permissions(Document, [PERMISSION_COMMENT_CREATE,
register_model_list_columns(Comment, [
{
'name': _(u'Date'),
'name': _('Date'),
'attribute': 'submit_date'
},
{
'name': _(u'User'),
'name': _('User'),
'attribute': encapsulate(lambda x: x.user.get_full_name() if x.user.get_full_name() else x.user)
},
{
'name': _(u'Comment'),
'name': _('Comment'),
'attribute': 'comment'
}
])

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django import forms
from django.contrib.comments.models import Comment

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals, absolute_import
from django.utils.translation import ugettext_lazy as _

View File

@@ -1,11 +1,11 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
comments_namespace = PermissionNamespace('comments', _(u'Comments'))
comments_namespace = PermissionNamespace('comments', _('Comments'))
PERMISSION_COMMENT_CREATE = Permission.objects.register(comments_namespace, 'comment_create', _(u'Create new comments'))
PERMISSION_COMMENT_DELETE = Permission.objects.register(comments_namespace, 'comment_delete', _(u'Delete comments'))
PERMISSION_COMMENT_VIEW = Permission.objects.register(comments_namespace, 'comment_view', _(u'View comments'))
PERMISSION_COMMENT_CREATE = Permission.objects.register(comments_namespace, 'comment_create', _('Create new comments'))
PERMISSION_COMMENT_DELETE = Permission.objects.register(comments_namespace, 'comment_delete', _('Delete comments'))
PERMISSION_COMMENT_VIEW = Permission.objects.register(comments_namespace, 'comment_view', _('View comments'))

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns('document_comments.views',

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.contrib import messages
from django.contrib.comments.models import Comment
@@ -16,8 +16,10 @@ from documents.models import Document
from permissions.models import Permission
from .forms import CommentForm
from .permissions import (PERMISSION_COMMENT_CREATE, PERMISSION_COMMENT_DELETE,
PERMISSION_COMMENT_VIEW)
from .permissions import (
PERMISSION_COMMENT_CREATE, PERMISSION_COMMENT_DELETE,
PERMISSION_COMMENT_VIEW
)
def comment_delete(request, comment_id=None, comment_id_list=None):
@@ -34,7 +36,7 @@ def comment_delete(request, comment_id=None, comment_id_list=None):
comments = AccessEntry.objects.filter_objects_by_access(PERMISSION_COMMENT_DELETE, request.user, comments, related='content_object')
if not comments:
messages.error(request, _(u'Must provide at least one comment.'))
messages.error(request, _('Must provide at least one comment.'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('main:home')))
previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', reverse('main:home'))))
@@ -44,9 +46,9 @@ def comment_delete(request, comment_id=None, comment_id_list=None):
for comment in comments:
try:
comment.delete()
messages.success(request, _(u'Comment "%s" deleted successfully.') % comment)
messages.success(request, _('Comment "%s" deleted successfully.') % comment)
except Exception as exception:
messages.error(request, _(u'Error deleting comment "%(comment)s": %(error)s') % {
messages.error(request, _('Error deleting comment "%(comment)s": %(error)s') % {
'comment': comment, 'error': exception
})
@@ -59,9 +61,9 @@ def comment_delete(request, comment_id=None, comment_id_list=None):
}
if len(comments) == 1:
context['object'] = comments[0].content_object
context['title'] = _(u'Are you sure you wish to delete the comment: %s?') % ', '.join([unicode(d) for d in comments])
context['title'] = _('Are you sure you wish to delete the comment: %s?') % ', '.join([unicode(d) for d in comments])
elif len(comments) > 1:
context['title'] = _(u'Are you sure you wish to delete the comments: %s?') % ', '.join([unicode(d) for d in comments])
context['title'] = _('Are you sure you wish to delete the comments: %s?') % ', '.join([unicode(d) for d in comments])
return render_to_response('main/generic_confirm.html', context,
context_instance=RequestContext(request))
@@ -95,14 +97,14 @@ def comment_add(request, document_id):
comment.site = Site.objects.get_current()
comment.save()
messages.success(request, _(u'Comment added successfully.'))
messages.success(request, _('Comment added successfully.'))
return HttpResponseRedirect(next)
else:
form = CommentForm()
return render_to_response('main/generic_form.html', {
'form': form,
'title': _(u'Add comment to document'),
'title': _('Add comment to document'),
'next': next,
'object': document,
}, context_instance=RequestContext(request))
@@ -122,7 +124,7 @@ def comments_for_document(request, document_id):
return render_to_response('main/generic_list.html', {
'object': document,
'access_object': document,
'title': _(u'Document comments'),
'title': _('Document comments'),
'object_list': Comment.objects.for_model(document).order_by('-submit_date'),
'hide_link': True,
'hide_object': True,

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
@@ -36,7 +36,7 @@ def document_metadata_index_post_delete(sender, **kwargs):
task_index_document.apply_async(kwargs=dict(document_id=kwargs['instance'].document.pk), queue='indexing')
register_maintenance_links([rebuild_index_instances], namespace='document_indexing', title=_(u'Indexes'))
register_maintenance_links([rebuild_index_instances], namespace='document_indexing', title=_('Indexes'))
register_links(Document, [document_index_list], menu_name='form_header')
register_links([Index, 'indexing:index_setup_list', 'indexing:index_setup_create'], [index_setup_list, index_setup_create], menu_name='secondary_menu')

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
@@ -47,7 +47,7 @@ def cascade_eval(document, template_node, parent_index_instance=None):
try:
result = eval(template_node.expression, {'document': document}, AVAILABLE_INDEXING_FUNCTIONS)
except Exception as exception:
error_message = _(u'Error indexing document: %(document)s; expression: %(expression)s; %(exception)s') % {
error_message = _('Error indexing document: %(document)s; expression: %(expression)s; %(exception)s') % {
'document': document, 'expression': template_node.expression, 'exception': exception}
warnings.append(error_message)
logger.debug(error_message)

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django import forms

View File

@@ -1,15 +1,15 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from documents.permissions import PERMISSION_DOCUMENT_VIEW
from .permissions import (PERMISSION_DOCUMENT_INDEXING_CREATE,
PERMISSION_DOCUMENT_INDEXING_EDIT,
PERMISSION_DOCUMENT_INDEXING_DELETE,
PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES,
PERMISSION_DOCUMENT_INDEXING_SETUP,
PERMISSION_DOCUMENT_INDEXING_VIEW)
from .permissions import (
PERMISSION_DOCUMENT_INDEXING_CREATE, PERMISSION_DOCUMENT_INDEXING_EDIT,
PERMISSION_DOCUMENT_INDEXING_DELETE,
PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES,
PERMISSION_DOCUMENT_INDEXING_SETUP, PERMISSION_DOCUMENT_INDEXING_VIEW
)
def is_not_instance_root_node(context):
@@ -20,23 +20,23 @@ def is_not_root_node(context):
return not context['node'].is_root_node()
index_setup = {'text': _(u'Indexes'), 'view': 'indexing:index_setup_list', 'icon': 'tab.png', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_list = {'text': _(u'Indexes'), 'view': 'indexing:index_setup_list', 'famfam': 'tab', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_create = {'text': _(u'Create index'), 'view': 'indexing:index_setup_create', 'famfam': 'tab_add', 'permissions': [PERMISSION_DOCUMENT_INDEXING_CREATE]}
index_setup_edit = {'text': _(u'Edit'), 'view': 'indexing:index_setup_edit', 'args': 'index.pk', 'famfam': 'tab_edit', 'permissions': [PERMISSION_DOCUMENT_INDEXING_EDIT]}
index_setup_delete = {'text': _(u'Delete'), 'view': 'indexing:index_setup_delete', 'args': 'index.pk', 'famfam': 'tab_delete', 'permissions': [PERMISSION_DOCUMENT_INDEXING_DELETE]}
index_setup_view = {'text': _(u'Tree template'), 'view': 'indexing:index_setup_view', 'args': 'index.pk', 'famfam': 'textfield', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_document_types = {'text': _(u'Document types'), 'view': 'indexing:index_setup_document_types', 'args': 'index.pk', 'famfam': 'layout', 'permissions': [PERMISSION_DOCUMENT_INDEXING_EDIT]}
index_setup = {'text': _('Indexes'), 'view': 'indexing:index_setup_list', 'icon': 'tab.png', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_list = {'text': _('Indexes'), 'view': 'indexing:index_setup_list', 'famfam': 'tab', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_create = {'text': _('Create index'), 'view': 'indexing:index_setup_create', 'famfam': 'tab_add', 'permissions': [PERMISSION_DOCUMENT_INDEXING_CREATE]}
index_setup_edit = {'text': _('Edit'), 'view': 'indexing:index_setup_edit', 'args': 'index.pk', 'famfam': 'tab_edit', 'permissions': [PERMISSION_DOCUMENT_INDEXING_EDIT]}
index_setup_delete = {'text': _('Delete'), 'view': 'indexing:index_setup_delete', 'args': 'index.pk', 'famfam': 'tab_delete', 'permissions': [PERMISSION_DOCUMENT_INDEXING_DELETE]}
index_setup_view = {'text': _('Tree template'), 'view': 'indexing:index_setup_view', 'args': 'index.pk', 'famfam': 'textfield', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
index_setup_document_types = {'text': _('Document types'), 'view': 'indexing:index_setup_document_types', 'args': 'index.pk', 'famfam': 'layout', 'permissions': [PERMISSION_DOCUMENT_INDEXING_EDIT]}
template_node_create = {'text': _(u'New child node'), 'view': 'indexing:template_node_create', 'args': 'node.pk', 'famfam': 'textfield_add', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
template_node_edit = {'text': _(u'Edit'), 'view': 'indexing:template_node_edit', 'args': 'node.pk', 'famfam': 'textfield', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP], 'condition': is_not_root_node}
template_node_delete = {'text': _(u'Delete'), 'view': 'indexing:template_node_delete', 'args': 'node.pk', 'famfam': 'textfield_delete', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP], 'condition': is_not_root_node}
template_node_create = {'text': _('New child node'), 'view': 'indexing:template_node_create', 'args': 'node.pk', 'famfam': 'textfield_add', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP]}
template_node_edit = {'text': _('Edit'), 'view': 'indexing:template_node_edit', 'args': 'node.pk', 'famfam': 'textfield', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP], 'condition': is_not_root_node}
template_node_delete = {'text': _('Delete'), 'view': 'indexing:template_node_delete', 'args': 'node.pk', 'famfam': 'textfield_delete', 'permissions': [PERMISSION_DOCUMENT_INDEXING_SETUP], 'condition': is_not_root_node}
index_list = {'text': _(u'Index list'), 'view': 'indexing:index_list', 'famfam': 'tab', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW]}
index_list = {'text': _('Index list'), 'view': 'indexing:index_list', 'famfam': 'tab', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW]}
index_parent = {'text': _(u'Go up one level'), 'view': 'indexing:index_instance_node_view', 'args': 'object.parent.pk', 'famfam': 'arrow_up', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW], 'dont_mark_active': True, 'condition': is_not_instance_root_node}
document_index_list = {'text': _(u'Indexes'), 'view': 'indexing:document_index_list', 'args': 'object.pk', 'famfam': 'folder_page', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW, PERMISSION_DOCUMENT_VIEW]}
index_parent = {'text': _('Go up one level'), 'view': 'indexing:index_instance_node_view', 'args': 'object.parent.pk', 'famfam': 'arrow_up', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW], 'dont_mark_active': True, 'condition': is_not_instance_root_node}
document_index_list = {'text': _('Indexes'), 'view': 'indexing:document_index_list', 'args': 'object.pk', 'famfam': 'folder_page', 'permissions': [PERMISSION_DOCUMENT_INDEXING_VIEW, PERMISSION_DOCUMENT_VIEW]}
document_index_main_menu_link = {'text': _('Indexes'), 'famfam': 'tab', 'view': 'indexing:index_list'}
rebuild_index_instances = {'text': _('Rebuild indexes'), 'view': 'indexing:rebuild_index_instances', 'famfam': 'folder_page', 'permissions': [PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES], 'description': _(u'Deletes and creates from scratch all the document indexes.')}
rebuild_index_instances = {'text': _('Rebuild indexes'), 'view': 'indexing:rebuild_index_instances', 'famfam': 'folder_page', 'permissions': [PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES], 'description': _('Deletes and creates from scratch all the document indexes.')}

View File

@@ -1,5 +1,3 @@
from __future__ import absolute_import
from django.db import models

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
@@ -12,11 +12,11 @@ from .managers import IndexManager
class Index(models.Model):
name = models.CharField(unique=True, max_length=64, verbose_name=_(u'Name'), help_text=_(u'Internal name used to reference this index.'))
name = models.CharField(unique=True, max_length=64, verbose_name=_('Name'), help_text=_('Internal name used to reference this index.'))
# TODO: normalize 'title' to 'label'
title = models.CharField(unique=True, max_length=128, verbose_name=_(u'Title'), help_text=_(u'The name that will be visible to users.'))
enabled = models.BooleanField(default=True, verbose_name=_(u'Enabled'), help_text=_(u'Causes this index to be visible and updated when document data changes.'))
document_types = models.ManyToManyField(DocumentType, verbose_name=_(u'Document types'))
title = models.CharField(unique=True, max_length=128, verbose_name=_('Title'), help_text=_('The name that will be visible to users.'))
enabled = models.BooleanField(default=True, verbose_name=_('Enabled'), help_text=_('Causes this index to be visible and updated when document data changes.'))
document_types = models.ManyToManyField(DocumentType, verbose_name=_('Document types'))
objects = IndexManager()
@@ -44,7 +44,7 @@ class Index(models.Model):
IndexTemplateNode.objects.get_or_create(parent=None, index=self)
def get_document_types_names(self):
return u', '.join([unicode(document_type) for document_type in self.document_types.all()] or [u'None'])
return ', '.join([unicode(document_type) for document_type in self.document_types.all()] or ['None'])
def natural_key(self):
return (self.name,)
@@ -56,30 +56,30 @@ class Index(models.Model):
return 0
class Meta:
verbose_name = _(u'Index')
verbose_name_plural = _(u'Indexes')
verbose_name = _('Index')
verbose_name_plural = _('Indexes')
class IndexTemplateNode(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True)
index = models.ForeignKey(Index, verbose_name=_(u'Index'), related_name='node_templates')
expression = models.CharField(max_length=128, verbose_name=_(u'Indexing expression'), help_text=_(u'Enter a python string expression to be evaluated.'))
enabled = models.BooleanField(default=True, verbose_name=_(u'Enabled'), help_text=_(u'Causes this node to be visible and updated when document data changes.'))
link_documents = models.BooleanField(default=False, verbose_name=_(u'Link documents'), help_text=_(u'Check this option to have this node act as a container for documents and not as a parent for further nodes.'))
index = models.ForeignKey(Index, verbose_name=_('Index'), related_name='node_templates')
expression = models.CharField(max_length=128, verbose_name=_('Indexing expression'), help_text=_('Enter a python string expression to be evaluated.'))
enabled = models.BooleanField(default=True, verbose_name=_('Enabled'), help_text=_('Causes this node to be visible and updated when document data changes.'))
link_documents = models.BooleanField(default=False, verbose_name=_('Link documents'), help_text=_('Check this option to have this node act as a container for documents and not as a parent for further nodes.'))
def __unicode__(self):
return self.expression
class Meta:
verbose_name = _(u'Index node template')
verbose_name_plural = _(u'Indexes node template')
verbose_name = _('Index node template')
verbose_name_plural = _('Indexes node template')
class IndexInstanceNode(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True)
index_template_node = models.ForeignKey(IndexTemplateNode, related_name='node_instance', verbose_name=_(u'Index template node'))
value = models.CharField(max_length=128, blank=True, verbose_name=_(u'Value'))
documents = models.ManyToManyField(Document, related_name='node_instances', verbose_name=_(u'Documents'))
index_template_node = models.ForeignKey(IndexTemplateNode, related_name='node_instance', verbose_name=_('Index template node'))
value = models.CharField(max_length=128, blank=True, verbose_name=_('Value'))
documents = models.ManyToManyField(Document, related_name='node_instances', verbose_name=_('Documents'))
def __unicode__(self):
return self.value
@@ -97,5 +97,5 @@ class IndexInstanceNode(MPTTModel):
return self.get_children()
class Meta:
verbose_name = _(u'Index node instance')
verbose_name_plural = _(u'Indexes node instances')
verbose_name = _('Index node instance')
verbose_name_plural = _('Indexes node instances')

View File

@@ -1,15 +1,15 @@
from __future__ import absolute_import
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
document_indexing_namespace = PermissionNamespace('document_indexing', _(u'Indexing'))
document_indexing_namespace = PermissionNamespace('document_indexing', _('Indexing'))
PERMISSION_DOCUMENT_INDEXING_SETUP = Permission.objects.register(document_indexing_namespace, 'document_index_setup', _(u'Configure document indexes'))
PERMISSION_DOCUMENT_INDEXING_CREATE = Permission.objects.register(document_indexing_namespace, 'document_index_create', _(u'Create new document indexes'))
PERMISSION_DOCUMENT_INDEXING_EDIT = Permission.objects.register(document_indexing_namespace, 'document_index_edit', _(u'Edit document indexes'))
PERMISSION_DOCUMENT_INDEXING_DELETE = Permission.objects.register(document_indexing_namespace, 'document_index_delete', _(u'Delete document indexes'))
PERMISSION_DOCUMENT_INDEXING_SETUP = Permission.objects.register(document_indexing_namespace, 'document_index_setup', _('Configure document indexes'))
PERMISSION_DOCUMENT_INDEXING_CREATE = Permission.objects.register(document_indexing_namespace, 'document_index_create', _('Create new document indexes'))
PERMISSION_DOCUMENT_INDEXING_EDIT = Permission.objects.register(document_indexing_namespace, 'document_index_edit', _('Edit document indexes'))
PERMISSION_DOCUMENT_INDEXING_DELETE = Permission.objects.register(document_indexing_namespace, 'document_index_delete', _('Delete document indexes'))
PERMISSION_DOCUMENT_INDEXING_VIEW = Permission.objects.register(document_indexing_namespace, 'document_index_view', _(u'View document indexes'))
PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES = Permission.objects.register(document_indexing_namespace, 'document_rebuild_indexes', _(u'Rebuild document indexes'))
PERMISSION_DOCUMENT_INDEXING_VIEW = Permission.objects.register(document_indexing_namespace, 'document_index_view', _('View document indexes'))
PERMISSION_DOCUMENT_INDEXING_REBUILD_INDEXES = Permission.objects.register(document_indexing_namespace, 'document_rebuild_indexes', _('Rebuild document indexes'))

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from rest_framework import serializers

View File

@@ -1,4 +1,4 @@
"""Configuration options for the document_indexing app"""
from __future__ import unicode_literals
from smart_settings.api import register_settings
@@ -6,10 +6,10 @@ available_indexing_functions = {
}
register_settings(
namespace=u'document_indexing',
module=u'document_indexing.settings',
namespace='document_indexing',
module='document_indexing.settings',
settings=[
# Definition
{'name': u'AVAILABLE_INDEXING_FUNCTIONS', 'global_name': u'DOCUMENT_INDEXING_AVAILABLE_INDEXING_FUNCTIONS', 'default': available_indexing_functions},
{'name': 'AVAILABLE_INDEXING_FUNCTIONS', 'global_name': 'DOCUMENT_INDEXING_AVAILABLE_INDEXING_FUNCTIONS', 'default': available_indexing_functions},
]
)

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
import logging
from mayan.celery import app

View File

@@ -1,4 +1,4 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from django.core.files.base import File
from django.test import TestCase
@@ -32,11 +32,11 @@ class IndexTestCase(TestCase):
# Create simple index template
root = index.template_root
index.node_templates.create(parent=root, expression='document.metadata_value_of.test', link_documents=True)
self.failUnlessEqual(list(IndexTemplateNode.objects.values_list('expression', flat=True)), [u'', u'document.metadata_value_of.test'])
self.failUnlessEqual(list(IndexTemplateNode.objects.values_list('expression', flat=True)), ['', 'document.metadata_value_of.test'])
# Add document metadata value to trigger index node instance creation
self.document.metadata.create(metadata_type=metadata_type, value='0001')
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [u'', u'0001'])
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), ['', '0001'])
# Check that document is in instance node
instance_node = IndexInstanceNode.objects.get(value='0001')
@@ -46,7 +46,7 @@ class IndexTestCase(TestCase):
document_metadata = self.document.metadata.get(metadata_type=metadata_type)
document_metadata.value = '0002'
document_metadata.save()
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [u'', u'0002'])
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), ['', '0002'])
# Check that document is in new instance node
instance_node = IndexInstanceNode.objects.get(value='0002')
@@ -54,12 +54,12 @@ class IndexTestCase(TestCase):
# Check node instance is destoyed when no metadata is available
self.document.metadata.get(metadata_type=metadata_type).delete()
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [u''])
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [''])
# Add document metadata value again to trigger index node instance creation
self.document.metadata.create(metadata_type=metadata_type, value='0003')
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [u'', u'0003'])
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), ['', '0003'])
# Check node instance is destroyed when no documents are contained
self.document.delete()
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [u''])
self.failUnlessEqual(list(IndexInstanceNode.objects.values_list('value', flat=True)), [''])

View File

@@ -1,5 +1,3 @@
from __future__ import absolute_import
from documents.models import Document
from .api import index_document

View File

@@ -1,3 +1,5 @@
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from .api_views import (APIDocumentIndexListView,

Some files were not shown because too many files have changed in this diff Show More