PEP8 all the things

This commit is contained in:
David Taylor
2017-09-22 14:57:14 +01:00
parent 131ff3e612
commit f9389e3996
19 changed files with 409 additions and 378 deletions

View File

@@ -10,6 +10,7 @@ https://docs.djangoproject.com/en/1.7/ref/settings/
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os import os
import raven
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
@@ -144,8 +145,6 @@ LOGGING = {
} }
} }
import raven
RAVEN_CONFIG = { RAVEN_CONFIG = {
'dsn': os.environ.get('RAVEN_DSN'), 'dsn': os.environ.get('RAVEN_DSN'),
# If you are using git, you can also automatically configure the # If you are using git, you can also automatically configure the

View File

@@ -9,7 +9,7 @@ https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
import os import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PyRIGS.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PyRIGS.settings")
from django.core.wsgi import get_wsgi_application from django.core.wsgi import get_wsgi_application # noqa
from dj_static import Cling from dj_static import Cling # noqa
application = Cling(get_wsgi_application()) application = Cling(get_wsgi_application())

View File

@@ -95,6 +95,7 @@ class InvoiceVoid(generic.View):
return HttpResponseRedirect(reverse_lazy('invoice_list')) return HttpResponseRedirect(reverse_lazy('invoice_list'))
return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': object.pk})) return HttpResponseRedirect(reverse_lazy('invoice_detail', kwargs={'pk': object.pk}))
class InvoiceDelete(generic.DeleteView): class InvoiceDelete(generic.DeleteView):
model = models.Invoice model = models.Invoice
@@ -115,6 +116,7 @@ class InvoiceDelete(generic.DeleteView):
def get_success_url(self): def get_success_url(self):
return self.request.POST.get('next') return self.request.POST.get('next')
class InvoiceArchive(generic.ListView): class InvoiceArchive(generic.ListView):
model = models.Invoice model = models.Invoice
template_name = 'RIGS/invoice_list_archive.html' template_name = 'RIGS/invoice_list_archive.html'
@@ -144,8 +146,8 @@ class InvoiceWaiting(generic.ListView):
( (
Q(start_date__lte=datetime.date.today(), end_date__isnull=True) | # Starts before with no end Q(start_date__lte=datetime.date.today(), end_date__isnull=True) | # Starts before with no end
Q(end_date__lte=datetime.date.today()) # Has end date, finishes before Q(end_date__lte=datetime.date.today()) # Has end date, finishes before
) & Q(invoice__isnull=True) # Has not already been invoiced ) & Q(invoice__isnull=True) & # Has not already been invoiced
& Q(is_rig=True) # Is a rig (not non-rig) Q(is_rig=True) # Is a rig (not non-rig)
).order_by('start_date') \ ).order_by('start_date') \
.select_related('person', .select_related('person',
@@ -176,7 +178,7 @@ class PaymentCreate(generic.CreateView):
def get_initial(self): def get_initial(self):
initial = super(generic.CreateView, self).get_initial() initial = super(generic.CreateView, self).get_initial()
invoicepk = self.request.GET.get('invoice', self.request.POST.get('invoice', None)) invoicepk = self.request.GET.get('invoice', self.request.POST.get('invoice', None))
if invoicepk == None: if invoicepk is None:
raise Http404() raise Http404()
invoice = get_object_or_404(models.Invoice, pk=invoicepk) invoice = get_object_or_404(models.Invoice, pk=invoicepk)
initial.update({'invoice': invoice}) initial.update({'invoice': invoice})

View File

@@ -1,4 +1,3 @@
__author__ = 'Ghost'
from django import forms from django import forms
from django.utils import formats from django.utils import formats
from django.conf import settings from django.conf import settings
@@ -16,6 +15,8 @@ forms.TimeField.widget = forms.TextInput(attrs={'type': 'time'})
forms.DateTimeField.widget = forms.DateTimeInput(attrs={'type': 'datetime-local'}) forms.DateTimeField.widget = forms.DateTimeInput(attrs={'type': 'datetime-local'})
# Registration # Registration
class ProfileRegistrationFormUniqueEmail(RegistrationFormUniqueEmail): class ProfileRegistrationFormUniqueEmail(RegistrationFormUniqueEmail):
captcha = ReCaptchaField() captcha = ReCaptchaField()

View File

@@ -5,7 +5,9 @@ from django.core.urlresolvers import reverse_lazy, reverse, NoReverseMatch
from django.utils import timezone from django.utils import timezone
from django.conf import settings from django.conf import settings
import datetime, pytz import datetime
import pytz
class CalendarICS(ICalFeed): class CalendarICS(ICalFeed):
""" """
@@ -97,7 +99,7 @@ class CalendarICS(ICalFeed):
return item.earliest_time return item.earliest_time
def item_end_datetime(self, item): def item_end_datetime(self, item):
if type(item.latest_time) is datetime.date: # Ical end_datetime is non-inclusive, so add a day if isinstance(item.latest_time, datetime.date): # Ical end_datetime is non-inclusive, so add a day
return item.latest_time + datetime.timedelta(days=1) return item.latest_time + datetime.timedelta(days=1)
return item.latest_time return item.latest_time
@@ -119,7 +121,6 @@ class CalendarICS(ICalFeed):
desc += 'Status = ' + str(item.get_status_display()) + '\n' desc += 'Status = ' + str(item.get_status_display()) + '\n'
desc += 'MIC = ' + (item.mic.name if item.mic else '---') + '\n' desc += 'MIC = ' + (item.mic.name if item.mic else '---') + '\n'
desc += '\n' desc += '\n'
if item.meet_at: if item.meet_at:
desc += 'Crew Meet = ' + (item.meet_at.astimezone(tz).strftime('%Y-%m-%d %H:%M') if item.meet_at else '---') + '\n' desc += 'Crew Meet = ' + (item.meet_at.astimezone(tz).strftime('%Y-%m-%d %H:%M') if item.meet_at else '---') + '\n'

View File

@@ -7,6 +7,8 @@ import datetime
import random import random
from RIGS import models from RIGS import models
class Command(BaseCommand): class Command(BaseCommand):
help = 'Adds sample data to use for testing' help = 'Adds sample data to use for testing'
can_import_settings = True can_import_settings = True
@@ -19,7 +21,6 @@ class Command(BaseCommand):
keyholder_group = None keyholder_group = None
finance_group = None finance_group = None
def handle(self, *args, **options): def handle(self, *args, **options):
from django.conf import settings from django.conf import settings
@@ -44,7 +45,8 @@ class Command(BaseCommand):
self.setupUsefulProfiles() self.setupUsefulProfiles()
def setupPeople(self): def setupPeople(self):
names = ["Regulus Black","Sirius Black","Lavender Brown","Cho Chang","Vincent Crabbe","Vincent Crabbe","Bartemius Crouch","Fleur Delacour","Cedric Diggory","Alberforth Dumbledore","Albus Dumbledore","Dudley Dursley","Petunia Dursley","Vernon Dursley","Argus Filch","Seamus Finnigan","Nicolas Flamel","Cornelius Fudge","Goyle","Gregory Goyle","Hermione Granger","Rubeus Hagrid","Igor Karkaroff","Viktor Krum","Bellatrix Lestrange","Alice Longbottom","Frank Longbottom","Neville Longbottom","Luna Lovegood","Xenophilius Lovegood","Remus Lupin","Draco Malfoy","Lucius Malfoy","Narcissa Malfoy","Olympe Maxime","Minerva McGonagall","Mad-Eye Moody","Peter Pettigrew","Harry Potter","James Potter","Lily Potter","Quirinus Quirrell","Tom Riddle","Mary Riddle","Lord Voldemort","Rita Skeeter","Severus Snape","Nymphadora Tonks","Dolores Janes Umbridge","Arthur Weasley","Bill Weasley","Charlie Weasley","Fred Weasley","George Weasley","Ginny Weasley","Molly Weasley","Percy Weasley","Ron Weasley","Dobby","Fluffy","Hedwig","Moaning Myrtle","Aragog","Grawp"] names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe", "Bartemius Crouch", "Fleur Delacour", "Cedric Diggory", "Alberforth Dumbledore", "Albus Dumbledore", "Dudley Dursley", "Petunia Dursley", "Vernon Dursley", "Argus Filch", "Seamus Finnigan", "Nicolas Flamel", "Cornelius Fudge", "Goyle", "Gregory Goyle", "Hermione Granger", "Rubeus Hagrid", "Igor Karkaroff", "Viktor Krum", "Bellatrix Lestrange", "Alice Longbottom", "Frank Longbottom", "Neville Longbottom", "Luna Lovegood", "Xenophilius Lovegood", # noqa
"Remus Lupin", "Draco Malfoy", "Lucius Malfoy", "Narcissa Malfoy", "Olympe Maxime", "Minerva McGonagall", "Mad-Eye Moody", "Peter Pettigrew", "Harry Potter", "James Potter", "Lily Potter", "Quirinus Quirrell", "Tom Riddle", "Mary Riddle", "Lord Voldemort", "Rita Skeeter", "Severus Snape", "Nymphadora Tonks", "Dolores Janes Umbridge", "Arthur Weasley", "Bill Weasley", "Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley", "Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): with reversion.create_revision():
reversion.set_user(random.choice(self.profiles)) reversion.set_user(random.choice(self.profiles))
@@ -66,7 +68,8 @@ class Command(BaseCommand):
self.people.append(newPerson) self.people.append(newPerson)
def setupOrganisations(self): def setupOrganisations(self):
names = ["Acme, inc.","Widget Corp","123 Warehousing","Demo Company","Smith and Co.","Foo Bars","ABC Telecom","Fake Brothers","QWERTY Logistics","Demo, inc.","Sample Company","Sample, inc","Acme Corp","Allied Biscuit","Ankh-Sto Associates","Extensive Enterprise","Galaxy Corp","Globo-Chem","Mr. Sparkle","Globex Corporation","LexCorp","LuthorCorp","North Central Positronics","Omni Consimer Products","Praxis Corporation","Sombra Corporation","Sto Plains Holdings","Tessier-Ashpool","Wayne Enterprises","Wentworth Industries","ZiffCorp","Bluth Company","Strickland Propane","Thatherton Fuels","Three Waters","Water and Power","Western Gas & Electric","Mammoth Pictures","Mooby Corp","Gringotts","Thrift Bank","Flowers By Irene","The Legitimate Businessmens Club","Osato Chemicals","Transworld Consortium","Universal Export","United Fried Chicken","Virtucon","Kumatsu Motors","Keedsler Motors","Powell Motors","Industrial Automation","Sirius Cybernetics Corporation","U.S. Robotics and Mechanical Men","Colonial Movers","Corellian Engineering Corporation","Incom Corporation","General Products","Leeding Engines Ltd.","Blammo","Input, Inc.","Mainway Toys","Videlectrix","Zevo Toys","Ajax","Axis Chemical Co.","Barrytron","Carrys Candles","Cogswell Cogs","Spacely Sprockets","General Forge and Foundry","Duff Brewing Company","Dunder Mifflin","General Services Corporation","Monarch Playing Card Co.","Krustyco","Initech","Roboto Industries","Primatech","Sonky Rubber Goods","St. Anky Beer","Stay Puft Corporation","Vandelay Industries","Wernham Hogg","Gadgetron","Burleigh and Stronginthearm","BLAND Corporation","Nordyne Defense Dynamics","Petrox Oil Company","Roxxon","McMahon and Tate","Sixty Second Avenue","Charles Townsend Agency","Spade and Archer","Megadodo Publications","Rouster and Sideways","C.H. Lavatory and Sons","Globo Gym American Corp","The New Firm","SpringShield","Compuglobalhypermeganet","Data Systems","Gizmonic Institute","Initrode","Taggart Transcontinental","Atlantic Northern","Niagular","Plow King","Big Kahuna Burger","Big T Burgers and Fries","Chez Quis","Chotchkies","The Frying Dutchman","Klimpys","The Krusty Krab","Monks Diner","Milliways","Minuteman Cafe","Taco Grande","Tip Top Cafe","Moes Tavern","Central Perk","Chasers"] names = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa
"Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): with reversion.create_revision():
reversion.set_user(random.choice(self.profiles)) reversion.set_user(random.choice(self.profiles))
@@ -90,7 +93,8 @@ class Command(BaseCommand):
self.organisations.append(newOrganisation) self.organisations.append(newOrganisation)
def setupVenues(self): def setupVenues(self):
names = ["Bear Island","Crossroads Inn","Deepwood Motte","The Dreadfort","The Eyrie","Greywater Watch","The Iron Islands","Karhold","Moat Cailin","Oldstones","Raventree Hall","Riverlands","The Ruby Ford","Saltpans","Seagard","Torrhen's Square","The Trident","The Twins","The Vale of Arryn","The Whispering Wood","White Harbor","Winterfell","The Arbor","Ashemark","Brightwater Keep","Casterly Rock","Clegane's Keep","Dragonstone","Dorne","God's Eye","The Golden Tooth","Harrenhal","Highgarden","Horn Hill","Fingers","King's Landing","Lannisport","Oldtown","Rainswood","Storm's End","Summerhall","Sunspear","Tarth","Castle Black","Craster's Keep","Fist of the First Men","The Frostfangs","The Gift","The Skirling Pass","The Wall","Asshai","Astapor","Braavos","The Dothraki Sea","Lys","Meereen","Myr","Norvos","Pentos","Qarth","Qohor","The Red Waste","Tyrosh","Vaes Dothrak","Valyria","Village of the Lhazareen","Volantis","Yunkai"] names = ["Bear Island", "Crossroads Inn", "Deepwood Motte", "The Dreadfort", "The Eyrie", "Greywater Watch", "The Iron Islands", "Karhold", "Moat Cailin", "Oldstones", "Raventree Hall", "Riverlands", "The Ruby Ford", "Saltpans", "Seagard", "Torrhen's Square", "The Trident", "The Twins", "The Vale of Arryn", "The Whispering Wood", "White Harbor", "Winterfell", "The Arbor", "Ashemark", "Brightwater Keep", "Casterly Rock", "Clegane's Keep", "Dragonstone", "Dorne", "God's Eye", "The Golden Tooth", # noqa
"Harrenhal", "Highgarden", "Horn Hill", "Fingers", "King's Landing", "Lannisport", "Oldtown", "Rainswood", "Storm's End", "Summerhall", "Sunspear", "Tarth", "Castle Black", "Craster's Keep", "Fist of the First Men", "The Frostfangs", "The Gift", "The Skirling Pass", "The Wall", "Asshai", "Astapor", "Braavos", "The Dothraki Sea", "Lys", "Meereen", "Myr", "Norvos", "Pentos", "Qarth", "Qohor", "The Red Waste", "Tyrosh", "Vaes Dothrak", "Valyria", "Village of the Lhazareen", "Volantis", "Yunkai"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): with reversion.create_revision():
reversion.set_user(random.choice(self.profiles)) reversion.set_user(random.choice(self.profiles))
@@ -163,7 +167,8 @@ class Command(BaseCommand):
basicUser.save() basicUser.save()
def setupEvents(self): def setupEvents(self):
names = ["Outdoor Concert","Hall Open Mic Night","Festival","Weekend Event","Magic Show","Society Ball","Evening Show","Talent Show","Acoustic Evening","Hire of Things","SU Event","End of Term Show","Theatre Show","Outdoor Fun Day","Summer Carnival","Open Days","Magic Show","Awards Ceremony","Debating Event","Club Night","DJ Evening","Building Projection","Choir Concert"] names = ["Outdoor Concert", "Hall Open Mic Night", "Festival", "Weekend Event", "Magic Show", "Society Ball", "Evening Show", "Talent Show", "Acoustic Evening", "Hire of Things", "SU Event",
"End of Term Show", "Theatre Show", "Outdoor Fun Day", "Summer Carnival", "Open Days", "Magic Show", "Awards Ceremony", "Debating Event", "Club Night", "DJ Evening", "Building Projection", "Choir Concert"]
descriptions = ["A brief desciption of the event", "This event is boring", "Probably wont happen", "Warning: this has lots of kit"] descriptions = ["A brief desciption of the event", "This event is boring", "Probably wont happen", "Warning: this has lots of kit"]
notes = ["The client came into the office at some point", "Who knows if this will happen", "Probably should check this event", "Maybe not happening", "Run away!"] notes = ["The client came into the office at some point", "Who knows if this will happen", "Probably should check this event", "Maybe not happening", "Run away!"]
@@ -200,7 +205,6 @@ class Command(BaseCommand):
elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=random.randint(1, 4)) newEvent.end_date = newEvent.start_date + datetime.timedelta(days=random.randint(1, 4))
if random.randint(0, 6) > 0: # 5 in 6 have MIC if random.randint(0, 6) > 0: # 5 in 6 have MIC
newEvent.mic = random.choice(self.profiles) newEvent.mic = random.choice(self.profiles)

View File

@@ -1,6 +1,7 @@
import datetime import datetime
import hashlib import hashlib
import datetime, pytz import datetime
import pytz
from django.db import models from django.db import models
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
@@ -32,7 +33,7 @@ class Profile(AbstractUser):
size = 20 size = 20
chars = string.ascii_letters + string.digits chars = string.ascii_letters + string.digits
new_api_key = ''.join(random.choice(chars) for x in range(size)) new_api_key = ''.join(random.choice(chars) for x in range(size))
return new_api_key; return new_api_key
@property @property
def profile_picture(self): def profile_picture(self):

View File

@@ -1,5 +1,7 @@
from RIGS.models import Profile from RIGS.models import Profile
from RIGS.forms import ProfileRegistrationFormUniqueEmail from RIGS.forms import ProfileRegistrationFormUniqueEmail
from registration.signals import user_registered
def user_created(sender, user, request, **kwargs): def user_created(sender, user, request, **kwargs):
form = ProfileRegistrationFormUniqueEmail(request.POST) form = ProfileRegistrationFormUniqueEmail(request.POST)
@@ -9,5 +11,5 @@ def user_created(sender, user, request, **kwargs):
user.phone = form.data['phone'] user.phone = form.data['phone']
user.save() user.save()
from registration.signals import user_registered
user_registered.connect(user_created) user_registered.connect(user_created)

View File

@@ -1,5 +1,7 @@
from io import BytesIO from io import BytesIO
import urllib.request, urllib.error, urllib.parse import urllib.request
import urllib.error
import urllib.parse
from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.mail import EmailMessage, EmailMultiAlternatives from django.core.mail import EmailMessage, EmailMultiAlternatives

View File

@@ -1,5 +1,7 @@
import re import re
import urllib.request, urllib.error, urllib.parse import urllib.request
import urllib.error
import urllib.parse
from io import BytesIO from io import BytesIO
from django.db.models.signals import post_save from django.db.models.signals import post_save

View File

@@ -5,14 +5,17 @@ from django.forms.utils import ErrorDict
register = template.Library() register = template.Library()
@register.filter @register.filter
def multiply(value, arg): def multiply(value, arg):
return value * arg return value * arg
@register.filter @register.filter
def to_class_name(value): def to_class_name(value):
return value.__class__.__name__ return value.__class__.__name__
@register.filter @register.filter
def nice_errors(form, non_field_msg='General form errors'): def nice_errors(form, non_field_msg='General form errors'):
nice_errors = ErrorDict() nice_errors = ErrorDict()
@@ -25,6 +28,7 @@ def nice_errors(form, non_field_msg='General form errors'):
nice_errors[key] = errors nice_errors[key] = errors
return nice_errors return nice_errors
def paginator(context, adjacent_pages=3): def paginator(context, adjacent_pages=3):
""" """
To be used in conjunction with the object_list generic view. To be used in conjunction with the object_list generic view.
@@ -37,10 +41,12 @@ def paginator(context, adjacent_pages=3):
page = context['page_obj'] page = context['page_obj']
paginator = context['paginator'] paginator = context['paginator']
startPage = max(page.number - adjacent_pages, 1) startPage = max(page.number - adjacent_pages, 1)
if startPage <= 3: startPage = 1 if startPage <= 3:
startPage = 1
endPage = page.number + adjacent_pages + 1 endPage = page.number + adjacent_pages + 1
if endPage >= paginator.num_pages - 1: endPage = paginator.num_pages + 1 if endPage >= paginator.num_pages - 1:
page_numbers = [n for n in range(startPage, endPage) \ endPage = paginator.num_pages + 1
page_numbers = [n for n in range(startPage, endPage)
if n > 0 and n <= paginator.num_pages] if n > 0 and n <= paginator.num_pages]
dict = { dict = {
@@ -64,8 +70,11 @@ def paginator(context, adjacent_pages=3):
dict['previous'] = page.previous_page_number() dict['previous'] = page.previous_page_number()
return dict return dict
register.inclusion_tag('pagination.html', takes_context=True)(paginator) register.inclusion_tag('pagination.html', takes_context=True)(paginator)
@register.simple_tag @register.simple_tag
def url_replace(request, field, value): def url_replace(request, field, value):
@@ -75,6 +84,7 @@ def url_replace(request, field, value):
return dict_.urlencode() return dict_.urlencode()
@register.simple_tag @register.simple_tag
def orderby(request, field, attr): def orderby(request, field, attr):

View File

@@ -35,6 +35,7 @@ def create_browser():
driver = webdriver.Chrome(chrome_options=options) driver = webdriver.Chrome(chrome_options=options)
return driver return driver
class UserRegistrationTest(LiveServerTestCase): class UserRegistrationTest(LiveServerTestCase):
def setUp(self): def setUp(self):
self.browser = create_browser() self.browser = create_browser()
@@ -166,6 +167,7 @@ class UserRegistrationTest(LiveServerTestCase):
# All is well # All is well
class EventTest(LiveServerTestCase): class EventTest(LiveServerTestCase):
def setUp(self): def setUp(self):
self.profile = models.Profile( self.profile = models.Profile(
@@ -173,7 +175,6 @@ class EventTest(LiveServerTestCase):
self.profile.set_password("EventTestPassword") self.profile.set_password("EventTestPassword")
self.profile.save() self.profile.save()
self.vatrate = models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1') self.vatrate = models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1')
self.browser = create_browser() self.browser = create_browser()
@@ -436,7 +437,7 @@ class EventTest(LiveServerTestCase):
self.assertFalse(error.is_displayed()) self.assertFalse(error.is_displayed())
except StaleElementReferenceException: except StaleElementReferenceException:
pass pass
except: except BaseException:
self.assertFail("Element does not appear to have been deleted") self.assertFail("Element does not appear to have been deleted")
# Check at least some data is preserved. Some = all will be there # Check at least some data is preserved. Some = all will be there
@@ -487,7 +488,6 @@ class EventTest(LiveServerTestCase):
self.browser.get(self.live_server_url + '/event/' + str(testEvent.pk) + '/duplicate/') self.browser.get(self.live_server_url + '/event/' + str(testEvent.pk) + '/duplicate/')
self.authenticate('/event/' + str(testEvent.pk) + '/duplicate/') self.authenticate('/event/' + str(testEvent.pk) + '/duplicate/')
wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations) wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations)
save = self.browser.find_element_by_xpath( save = self.browser.find_element_by_xpath(
@@ -543,7 +543,6 @@ class EventTest(LiveServerTestCase):
# Check the PO hasn't carried through # Check the PO hasn't carried through
self.assertNotIn("TESTPO", infoPanel.find_element_by_xpath('//dt[text()="PO"]/following-sibling::dd[1]').text) self.assertNotIn("TESTPO", infoPanel.find_element_by_xpath('//dt[text()="PO"]/following-sibling::dd[1]').text)
self.assertIn("N%05d" % testEvent.pk, infoPanel.find_element_by_xpath('//dt[text()="Based On"]/following-sibling::dd[1]').text) self.assertIn("N%05d" % testEvent.pk, infoPanel.find_element_by_xpath('//dt[text()="Based On"]/following-sibling::dd[1]').text)
self.browser.get(self.live_server_url + '/event/' + str(testEvent.pk)) # Go back to the old event self.browser.get(self.live_server_url + '/event/' + str(testEvent.pk)) # Go back to the old event
@@ -568,7 +567,6 @@ class EventTest(LiveServerTestCase):
# Gets redirected to login and back # Gets redirected to login and back
self.authenticate('/event/create/') self.authenticate('/event/create/')
wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations) wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations)
wait.until(animation_is_finished()) wait.until(animation_is_finished())
@@ -653,7 +651,6 @@ class EventTest(LiveServerTestCase):
self.browser.execute_script("document.getElementById('id_start_date').value='3015-04-24'") self.browser.execute_script("document.getElementById('id_start_date').value='3015-04-24'")
self.browser.execute_script("document.getElementById('id_end_date').value='3015-04-26'") self.browser.execute_script("document.getElementById('id_end_date').value='3015-04-26'")
self.browser.execute_script("document.getElementById('id_start_time').value=''") self.browser.execute_script("document.getElementById('id_start_time').value=''")
self.browser.execute_script("document.getElementById('id_end_time').value=''") self.browser.execute_script("document.getElementById('id_end_time').value=''")
@@ -671,7 +668,6 @@ class EventTest(LiveServerTestCase):
# Gets redirected to login and back # Gets redirected to login and back
self.authenticate('/event/create/') self.authenticate('/event/create/')
wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations) wait = WebDriverWait(self.browser, 3) # setup WebDriverWait to use later (to wait for animations)
self.browser.implicitly_wait(3) # Set session-long wait (only works for non-existant DOM objects) self.browser.implicitly_wait(3) # Set session-long wait (only works for non-existant DOM objects)
@@ -750,7 +746,6 @@ class EventTest(LiveServerTestCase):
organisationPanel = self.browser.find_element_by_xpath('//div[contains(text(), "Contact Details")]/..') organisationPanel = self.browser.find_element_by_xpath('//div[contains(text(), "Contact Details")]/..')
def testEventEdit(self): def testEventEdit(self):
person = models.Person(name="Event Edit Person", email="eventdetail@person.tests.rigs", phone="123 123").save() person = models.Person(name="Event Edit Person", email="eventdetail@person.tests.rigs", phone="123 123").save()
organisation = models.Organisation(name="Event Edit Organisation", email="eventdetail@organisation.tests.rigs", phone="123 456").save() organisation = models.Organisation(name="Event Edit Organisation", email="eventdetail@organisation.tests.rigs", phone="123 456").save()
@@ -810,6 +805,7 @@ class EventTest(LiveServerTestCase):
tz = pytz.timezone(settings.TIME_ZONE) tz = pytz.timezone(settings.TIME_ZONE)
return tz.localize(datetime(year, month, day, hour, min)).astimezone(pytz.utc) return tz.localize(datetime(year, month, day, hour, min)).astimezone(pytz.utc)
class IcalTest(LiveServerTestCase): class IcalTest(LiveServerTestCase):
def setUp(self): def setUp(self):
self.all_events = set(range(1, 18)) self.all_events = set(range(1, 18))
@@ -871,7 +867,6 @@ class IcalTest(LiveServerTestCase):
models.Event.objects.create(name="TE E18", start_date=date.today(), is_rig=False, status=models.Event.CANCELLED, models.Event.objects.create(name="TE E18", start_date=date.today(), is_rig=False, status=models.Event.CANCELLED,
description="non rig today cancelled") description="non rig today cancelled")
self.browser = create_browser() self.browser = create_browser()
self.browser.implicitly_wait(3) # Set implicit wait session wide self.browser.implicitly_wait(3) # Set implicit wait session wide
os.environ['RECAPTCHA_TESTING'] = 'True' os.environ['RECAPTCHA_TESTING'] = 'True'

View File

@@ -575,4 +575,3 @@ class RIGSVersionTestCase(TestCase):
self.assertEqual(diffs[0].old.name, "New Name") self.assertEqual(diffs[0].old.name, "New Name")
self.assertTrue(diffs[0].new is None) self.assertTrue(diffs[0].new is None)

View File

@@ -9,6 +9,7 @@ from django.test.utils import override_settings
from RIGS import models from RIGS import models
from reversion import revisions as reversion from reversion import revisions as reversion
class TestAdminMergeObjects(TestCase): class TestAdminMergeObjects(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):
@@ -159,6 +160,7 @@ class TestAdminMergeObjects(TestCase):
continue continue
self.assertEqual(updatedEvent.organisation, self.organisations[1]) self.assertEqual(updatedEvent.organisation, self.organisations[1])
class TestInvoiceDelete(TestCase): class TestInvoiceDelete(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):
@@ -327,7 +329,6 @@ class TestVersioningViews(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
class TestEmbeddedViews(TestCase): class TestEmbeddedViews(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):

View File

@@ -9,7 +9,8 @@ from django.core import serializers
from django.conf import settings from django.conf import settings
import simplejson import simplejson
from django.contrib import messages from django.contrib import messages
import datetime, pytz import datetime
import pytz
import operator import operator
from registration.views import RegistrationView from registration.views import RegistrationView
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
@@ -21,6 +22,8 @@ from functools import reduce
""" """
Displays the current rig count along with a few other bits and pieces Displays the current rig count along with a few other bits and pieces
""" """
class Index(generic.TemplateView): class Index(generic.TemplateView):
template_name = 'RIGS/index.html' template_name = 'RIGS/index.html'
@@ -29,6 +32,7 @@ class Index(generic.TemplateView):
context['rig_count'] = models.Event.objects.rig_count() context['rig_count'] = models.Event.objects.rig_count()
return context return context
def login(request, **kwargs): def login(request, **kwargs):
if request.user.is_authenticated(): if request.user.is_authenticated():
next = request.GET.get('next', '/') next = request.GET.get('next', '/')
@@ -61,12 +65,13 @@ def login_embed(request, **kwargs):
return login(request, template_name="registration/login_embed.html") return login(request, template_name="registration/login_embed.html")
""" """
Called from a modal window (e.g. when an item is submitted to an event/invoice). Called from a modal window (e.g. when an item is submitted to an event/invoice).
May optionally also include some javascript in a success message to cause a load of May optionally also include some javascript in a success message to cause a load of
the new information onto the page. the new information onto the page.
""" """
class CloseModal(generic.TemplateView): class CloseModal(generic.TemplateView):
template_name = 'closemodal.html' template_name = 'closemodal.html'
@@ -300,7 +305,6 @@ class SecureAPIRequest(generic.View):
qs.append(q) qs.append(q)
queries.append(reduce(operator.or_, qs)) queries.append(reduce(operator.or_, qs))
# Build the data response list # Build the data response list
results = [] results = []
query = reduce(operator.and_, queries) query = reduce(operator.and_, queries)
@@ -349,6 +353,7 @@ class SecureAPIRequest(generic.View):
return HttpResponse(model) return HttpResponse(model)
class ProfileDetail(generic.DetailView): class ProfileDetail(generic.DetailView):
model = models.Profile model = models.Profile
@@ -361,6 +366,7 @@ class ProfileDetail(generic.DetailView):
return self.model.objects.filter(pk=pk) return self.model.objects.filter(pk=pk)
class ProfileUpdateSelf(generic.UpdateView): class ProfileUpdateSelf(generic.UpdateView):
model = models.Profile model = models.Profile
fields = ['first_name', 'last_name', 'email', 'initials', 'phone'] fields = ['first_name', 'last_name', 'email', 'initials', 'phone']
@@ -375,6 +381,7 @@ class ProfileUpdateSelf(generic.UpdateView):
url = reverse_lazy('profile_detail') url = reverse_lazy('profile_detail')
return url return url
class ResetApiKey(generic.RedirectView): class ResetApiKey(generic.RedirectView):
def get_redirect_url(self, *args, **kwargs): def get_redirect_url(self, *args, **kwargs):
self.request.user.api_key = self.request.user.make_api_key() self.request.user.api_key = self.request.user.make_api_key()

View File

@@ -19,6 +19,7 @@ from multiprocessing import Process
# Slight fix for needing to restablish the connection # Slight fix for needing to restablish the connection
connection.close() connection.close()
def fix_email(email): def fix_email(email):
if not (email is None or email is "") and ("@" not in email): if not (email is None or email is "") and ("@" not in email):
email += "@nottingham.ac.uk" email += "@nottingham.ac.uk"
@@ -258,7 +259,7 @@ def import_nonrigs(delete=False):
if (delete): if (delete):
try: try:
models.Event.objects.filter(is_rig=False).delete() models.Event.objects.filter(is_rig=False).delete()
except: except BaseException:
pass pass
cursor = setup_cursor() cursor = setup_cursor()
if cursor is None: if cursor is None:
@@ -286,7 +287,7 @@ def import_invoices(delete=False):
try: try:
models.Invoice.objects.all().delete() models.Invoice.objects.all().delete()
models.Payment.objects.all().delete() models.Payment.objects.all().delete()
except: except BaseException:
pass pass
cursor = setup_cursor() cursor = setup_cursor()
if cursor is None: if cursor is None:
@@ -332,6 +333,7 @@ def import_invoices(delete=False):
p2.date = datetime.date.today() p2.date = datetime.date.today()
p2.save() p2.save()
@transaction.atomic @transaction.atomic
def main(): def main():
# processs = [] # processs = []
@@ -368,5 +370,6 @@ def main():
cursor = connections['default'].cursor() cursor = connections['default'].cursor()
cursor.execute(sql) cursor.execute(sql)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

2
setup.cfg Normal file
View File

@@ -0,0 +1,2 @@
[pep8]
max-line-length = 320