PEP8 format files

This commit is contained in:
Tom Price
2016-04-06 21:53:38 +01:00
parent ebe08c3bf1
commit 823db68a6a
2 changed files with 92 additions and 79 deletions

View File

@@ -6,7 +6,7 @@ import reversion
from django.contrib.admin import helpers from django.contrib.admin import helpers
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.contrib import messages from django.contrib import messages
from django.db import transaction from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count from django.db.models import Count
@@ -19,16 +19,17 @@ admin.site.register(models.EventItem, reversion.VersionAdmin)
admin.site.register(models.Invoice) admin.site.register(models.Invoice)
admin.site.register(models.Payment) admin.site.register(models.Payment)
@admin.register(models.Profile) @admin.register(models.Profile)
class ProfileAdmin(UserAdmin): class ProfileAdmin(UserAdmin):
fieldsets = ( fieldsets = (
(None, {'fields': ('username', 'password')}), (None, {'fields': ('username', 'password')}),
(_('Personal info'), { (_('Personal info'), {
'fields': ('first_name', 'last_name', 'email', 'initials', 'phone')}), 'fields': ('first_name', 'last_name', 'email', 'initials', 'phone')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}), 'groups', 'user_permissions')}),
(_('Important dates'), { (_('Important dates'), {
'fields': ('last_login', 'date_joined')}), 'fields': ('last_login', 'date_joined')}),
) )
add_fieldsets = ( add_fieldsets = (
(None, { (None, {
@@ -39,41 +40,43 @@ class ProfileAdmin(UserAdmin):
form = forms.ProfileChangeForm form = forms.ProfileChangeForm
add_form = forms.ProfileCreationForm add_form = forms.ProfileCreationForm
class AssociateAdmin(reversion.VersionAdmin): class AssociateAdmin(reversion.VersionAdmin):
list_display = ('id', 'name','number_of_events') list_display = ('id', 'name', 'number_of_events')
search_fields = ['id','name'] search_fields = ['id', 'name']
list_display_links = ['id','name'] list_display_links = ['id', 'name']
actions = ['merge'] actions = ['merge']
merge_fields = ['name'] merge_fields = ['name']
def get_queryset(self, request): def get_queryset(self, request):
return super(AssociateAdmin, self).get_queryset(request).annotate(event_count = Count('event')) return super(AssociateAdmin, self).get_queryset(request).annotate(event_count=Count('event'))
def number_of_events(self,obj): def number_of_events(self, obj):
return obj.latest_events.count() return obj.latest_events.count()
number_of_events.admin_order_field = 'event_count' number_of_events.admin_order_field = 'event_count'
def merge(self, request, queryset): def merge(self, request, queryset):
if request.POST.get('post'): # Has the user confirmed which is the master record? if request.POST.get('post'): # Has the user confirmed which is the master record?
try: try:
masterObjectPk = request.POST.get('master') masterObjectPk = request.POST.get('master')
masterObject = queryset.get(pk = masterObjectPk) masterObject = queryset.get(pk=masterObjectPk)
except ObjectDoesNotExist: except ObjectDoesNotExist:
self.message_user(request, "An error occured. Did you select a 'master' record?",level=messages.ERROR) self.message_user(request, "An error occured. Did you select a 'master' record?", level=messages.ERROR)
return return
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
for obj in queryset.exclude(pk = masterObjectPk): for obj in queryset.exclude(pk=masterObjectPk):
events = obj.event_set.all() events = obj.event_set.all()
for event in events: for event in events:
masterObject.event_set.add(event) masterObject.event_set.add(event)
obj.delete() obj.delete()
reversion.set_comment('Merging Objects') reversion.set_comment('Merging Objects')
self.message_user(request, "Objects successfully merged.") self.message_user(request, "Objects successfully merged.")
return return
else: # Present the confirmation screen else: # Present the confirmation screen
class TempForm(ModelForm): class TempForm(ModelForm):
class Meta: class Meta:
@@ -90,19 +93,23 @@ class AssociateAdmin(reversion.VersionAdmin):
'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
'forms': forms 'forms': forms
} }
return TemplateResponse(request, 'RIGS/admin_associate_merge.html', context, current_app=self.admin_site.name) return TemplateResponse(request, 'RIGS/admin_associate_merge.html', context,
current_app=self.admin_site.name)
@admin.register(models.Person) @admin.register(models.Person)
class PersonAdmin(AssociateAdmin): class PersonAdmin(AssociateAdmin):
list_display = ('id', 'name','phone','email','number_of_events') list_display = ('id', 'name', 'phone', 'email', 'number_of_events')
merge_fields = ['name','phone','email','address','notes'] merge_fields = ['name', 'phone', 'email', 'address', 'notes']
@admin.register(models.Venue) @admin.register(models.Venue)
class VenueAdmin(AssociateAdmin): class VenueAdmin(AssociateAdmin):
list_display = ('id', 'name','phone','email','number_of_events') list_display = ('id', 'name', 'phone', 'email', 'number_of_events')
merge_fields = ['name','phone','email','address','notes','three_phase_available'] merge_fields = ['name', 'phone', 'email', 'address', 'notes', 'three_phase_available']
@admin.register(models.Organisation) @admin.register(models.Organisation)
class OrganisationAdmin(AssociateAdmin): class OrganisationAdmin(AssociateAdmin):
list_display = ('id', 'name','phone','email','number_of_events') list_display = ('id', 'name', 'phone', 'email', 'number_of_events')
merge_fields = ['name','phone','email','address','notes','union_account'] merge_fields = ['name', 'phone', 'email', 'address', 'notes', 'union_account']

View File

@@ -14,7 +14,7 @@ from django.core.exceptions import ObjectDoesNotExist
import reversion import reversion
import simplejson import simplejson
from reversion.models import Version from reversion.models import Version
from django.contrib.contenttypes.models import ContentType # Used to lookup the content_type from django.contrib.contenttypes.models import ContentType # Used to lookup the content_type
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import ForeignKey, IntegerField, EmailField, TextField from django.db.models import ForeignKey, IntegerField, EmailField, TextField
from diff_match_patch import diff_match_patch from diff_match_patch import diff_match_patch
@@ -29,11 +29,10 @@ logger = logging.getLogger('tec.pyrigs')
def model_compare(oldObj, newObj, excluded_keys=[]): def model_compare(oldObj, newObj, excluded_keys=[]):
# recieves two objects of the same model, and compares them. Returns an array of FieldCompare objects # recieves two objects of the same model, and compares them. Returns an array of FieldCompare objects
try: try:
theFields = oldObj._meta.fields #This becomes deprecated in Django 1.8!!!!!!!!!!!!! (but an alternative becomes available) theFields = oldObj._meta.fields # This becomes deprecated in Django 1.8!!!!!!!!!!!!! (but an alternative becomes available)
except AttributeError: except AttributeError:
theFields = newObj._meta.fields theFields = newObj._meta.fields
class FieldCompare(object): class FieldCompare(object):
def __init__(self, field=None, old=None, new=None): def __init__(self, field=None, old=None, new=None):
self.field = field self.field = field
@@ -51,13 +50,13 @@ def model_compare(oldObj, newObj, excluded_keys=[]):
@property @property
def new(self): def new(self):
return self.display_value(self._new) return self.display_value(self._new)
@property @property
def long(self): def long(self):
if isinstance(self.field, EmailField): if isinstance(self.field, EmailField):
return True return True
return False return False
@property @property
def linebreaks(self): def linebreaks(self):
@@ -76,21 +75,21 @@ def model_compare(oldObj, newObj, excluded_keys=[]):
outputDiffs = [] outputDiffs = []
for (op, data) in diffs: for (op, data) in diffs:
if op == dmp.DIFF_INSERT: if op == dmp.DIFF_INSERT:
outputDiffs.append({'type':'insert', 'text':data}) outputDiffs.append({'type': 'insert', 'text': data})
elif op == dmp.DIFF_DELETE: elif op == dmp.DIFF_DELETE:
outputDiffs.append({'type':'delete', 'text':data}) outputDiffs.append({'type': 'delete', 'text': data})
elif op == dmp.DIFF_EQUAL: elif op == dmp.DIFF_EQUAL:
outputDiffs.append({'type':'equal', 'text':data}) outputDiffs.append({'type': 'equal', 'text': data})
return outputDiffs return outputDiffs
changes = [] changes = []
for thisField in theFields: for thisField in theFields:
name = thisField.name name = thisField.name
if name in excluded_keys: if name in excluded_keys:
continue # if we're excluding this field, skip over it continue # if we're excluding this field, skip over it
try: try:
oldValue = getattr(oldObj, name, None) oldValue = getattr(oldObj, name, None)
@@ -101,17 +100,18 @@ def model_compare(oldObj, newObj, excluded_keys=[]):
newValue = getattr(newObj, name, None) newValue = getattr(newObj, name, None)
except ObjectDoesNotExist: except ObjectDoesNotExist:
newValue = None newValue = None
try: try:
bothBlank = (not oldValue) and (not newValue) bothBlank = (not oldValue) and (not newValue)
if oldValue != newValue and not bothBlank: if oldValue != newValue and not bothBlank:
compare = FieldCompare(thisField,oldValue,newValue) compare = FieldCompare(thisField, oldValue, newValue)
changes.append(compare) changes.append(compare)
except TypeError: # logs issues with naive vs tz-aware datetimes except TypeError: # logs issues with naive vs tz-aware datetimes
logger.error('TypeError when comparing models') logger.error('TypeError when comparing models')
return changes return changes
def compare_event_items(old, new): def compare_event_items(old, new):
# Recieves two event version objects and compares their items, returns an array of ItemCompare objects # Recieves two event version objects and compares their items, returns an array of ItemCompare objects
@@ -126,39 +126,41 @@ def compare_event_items(old, new):
self.changes = changes self.changes = changes
# Build some dicts of what we have # Build some dicts of what we have
item_dict = {} # build a list of items, key is the item_pk item_dict = {} # build a list of items, key is the item_pk
for version in old_item_versions: # put all the old versions in a list for version in old_item_versions: # put all the old versions in a list
compare = ItemCompare(old=version.object_version.object) compare = ItemCompare(old=version.object_version.object)
item_dict[version.object_id] = compare item_dict[version.object_id] = compare
for version in new_item_versions: # go through the new versions for version in new_item_versions: # go through the new versions
try: try:
compare = item_dict[version.object_id] # see if there's a matching old version compare = item_dict[version.object_id] # see if there's a matching old version
compare.new = version.object_version.object # then add the new version to the dictionary compare.new = version.object_version.object # then add the new version to the dictionary
except KeyError: # there's no matching old version, so add this item to the dictionary by itself except KeyError: # there's no matching old version, so add this item to the dictionary by itself
compare = ItemCompare(new=version.object_version.object) compare = ItemCompare(new=version.object_version.object)
item_dict[version.object_id] = compare # update the dictionary with the changes
changes = [] item_dict[version.object_id] = compare # update the dictionary with the changes
changes = []
for (_, compare) in item_dict.items(): for (_, compare) in item_dict.items():
compare.changes = model_compare(compare.old, compare.new, ['id','event','order']) # see what's changed compare.changes = model_compare(compare.old, compare.new, ['id', 'event', 'order']) # see what's changed
if len(compare.changes) >= 1: if len(compare.changes) >= 1:
changes.append(compare) # transfer into a sequential array to make it easier to deal with later changes.append(compare) # transfer into a sequential array to make it easier to deal with later
return changes return changes
def get_versions_for_model(models): def get_versions_for_model(models):
content_types = [] content_types = []
for model in models: for model in models:
content_types.append(ContentType.objects.get_for_model(model)) content_types.append(ContentType.objects.get_for_model(model))
versions = reversion.models.Version.objects.filter( versions = reversion.models.Version.objects.filter(
content_type__in = content_types, content_type__in=content_types,
).select_related("revision").order_by("-pk") ).select_related("revision").order_by("-pk")
return versions return versions
def get_previous_version(version): def get_previous_version(version):
thisId = version.object_id thisId = version.object_id
thisVersionId = version.pk thisVersionId = version.pk
@@ -166,17 +168,19 @@ def get_previous_version(version):
versions = reversion.get_for_object_reference(version.content_type.model_class(), thisId) versions = reversion.get_for_object_reference(version.content_type.model_class(), thisId)
try: try:
previousVersions = versions.filter(revision_id__lt=version.revision_id).latest(field_name='revision__date_created') previousVersions = versions.filter(revision_id__lt=version.revision_id).latest(
field_name='revision__date_created')
except ObjectDoesNotExist: except ObjectDoesNotExist:
return False return False
return previousVersions return previousVersions
def get_changes_for_version(newVersion, oldVersion=None):
#Pass in a previous version if you already know it (for efficiancy)
#if not provided then it will be looked up in the database
if oldVersion == None: def get_changes_for_version(newVersion, oldVersion=None):
# Pass in a previous version if you already know it (for efficiancy)
# if not provided then it will be looked up in the database
if oldVersion == None:
oldVersion = get_previous_version(newVersion) oldVersion = get_previous_version(newVersion)
modelClass = newVersion.content_type.model_class() modelClass = newVersion.content_type.model_class()
@@ -200,6 +204,7 @@ def get_changes_for_version(newVersion, oldVersion=None):
return compare return compare
class VersionHistory(generic.ListView): class VersionHistory(generic.ListView):
model = reversion.revisions.Version model = reversion.revisions.Version
template_name = "RIGS/version_history.html" template_name = "RIGS/version_history.html"
@@ -215,7 +220,7 @@ class VersionHistory(generic.ListView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
thisModel = self.kwargs['model'] thisModel = self.kwargs['model']
context = super(VersionHistory, self).get_context_data(**kwargs) context = super(VersionHistory, self).get_context_data(**kwargs)
versions = context['object_list'] versions = context['object_list']
@@ -224,81 +229,82 @@ class VersionHistory(generic.ListView):
items = [] items = []
for versionNo, thisVersion in enumerate(versions): for versionNo, thisVersion in enumerate(versions):
if versionNo >= len(versions)-1: if versionNo >= len(versions) - 1:
thisItem = get_changes_for_version(thisVersion, None) thisItem = get_changes_for_version(thisVersion, None)
else: else:
thisItem = get_changes_for_version(thisVersion, versions[versionNo+1]) thisItem = get_changes_for_version(thisVersion, versions[versionNo + 1])
items.append(thisItem) items.append(thisItem)
context['object_list'] = items context['object_list'] = items
context['object'] = thisObject context['object'] = thisObject
return context return context
class ActivityTable(generic.ListView): class ActivityTable(generic.ListView):
model = reversion.revisions.Version model = reversion.revisions.Version
template_name = "RIGS/activity_table.html" template_name = "RIGS/activity_table.html"
paginate_by = 25 paginate_by = 25
def get_queryset(self): def get_queryset(self):
versions = get_versions_for_model([models.Event,models.Venue,models.Person,models.Organisation]) versions = get_versions_for_model([models.Event, models.Venue, models.Person, models.Organisation])
return versions return versions
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# Call the base implementation first to get a context # Call the base implementation first to get a context
context = super(ActivityTable, self).get_context_data(**kwargs) context = super(ActivityTable, self).get_context_data(**kwargs)
items = [] items = []
for thisVersion in context['object_list']: for thisVersion in context['object_list']:
thisItem = get_changes_for_version(thisVersion, None) thisItem = get_changes_for_version(thisVersion, None)
items.append(thisItem) items.append(thisItem)
context ['object_list'] = items context['object_list'] = items
return context return context
class ActivityFeed(generic.ListView): class ActivityFeed(generic.ListView):
model = reversion.revisions.Version model = reversion.revisions.Version
template_name = "RIGS/activity_feed_data.html" template_name = "RIGS/activity_feed_data.html"
paginate_by = 25 paginate_by = 25
def get_queryset(self): def get_queryset(self):
versions = get_versions_for_model([models.Event,models.Venue,models.Person,models.Organisation]) versions = get_versions_for_model([models.Event, models.Venue, models.Person, models.Organisation])
return versions return versions
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
maxTimeDelta = [] maxTimeDelta = []
maxTimeDelta.append({ 'maxAge':datetime.timedelta(days=1), 'group':datetime.timedelta(hours=1)}) maxTimeDelta.append({'maxAge': datetime.timedelta(days=1), 'group': datetime.timedelta(hours=1)})
maxTimeDelta.append({ 'maxAge':None, 'group':datetime.timedelta(days=1)}) maxTimeDelta.append({'maxAge': None, 'group': datetime.timedelta(days=1)})
# Call the base implementation first to get a context # Call the base implementation first to get a context
context = super(ActivityFeed, self).get_context_data(**kwargs) context = super(ActivityFeed, self).get_context_data(**kwargs)
items = [] items = []
for thisVersion in context['object_list']: for thisVersion in context['object_list']:
thisItem = get_changes_for_version(thisVersion, None) thisItem = get_changes_for_version(thisVersion, None)
if thisItem['item_changes'] or thisItem['field_changes'] or thisItem['old'] == None: if thisItem['item_changes'] or thisItem['field_changes'] or thisItem['old'] == None:
thisItem['withPrevious'] = False thisItem['withPrevious'] = False
if len(items)>=1: if len(items) >= 1:
timeAgo = datetime.datetime.now(thisItem['revision'].date_created.tzinfo) - thisItem['revision'].date_created timeAgo = datetime.datetime.now(thisItem['revision'].date_created.tzinfo) - thisItem[
'revision'].date_created
timeDiff = items[-1]['revision'].date_created - thisItem['revision'].date_created timeDiff = items[-1]['revision'].date_created - thisItem['revision'].date_created
timeTogether = False timeTogether = False
for params in maxTimeDelta: for params in maxTimeDelta:
if params['maxAge'] is None or timeAgo <= params['maxAge']: if params['maxAge'] is None or timeAgo <= params['maxAge']:
timeTogether = timeDiff < params['group'] timeTogether = timeDiff < params['group']
break break
sameUser = thisItem['revision'].user == items[-1]['revision'].user sameUser = thisItem['revision'].user == items[-1]['revision'].user
thisItem['withPrevious'] = timeTogether & sameUser thisItem['withPrevious'] = timeTogether & sameUser
items.append(thisItem) items.append(thisItem)
context ['object_list'] = items context['object_list'] = items
return context return context