1. Nathaniel Tucker
  2. ahgl

Commits

Wraithan  committed c6d1874

Cleaned up code a bunch. Not completely pep8/pyflakes on its way there.

  • Participants
  • Parent commits 702d4ec
  • Branches default

Comments (0)

Files changed (30)

File ahgl/__init__.py

View file
  • Ignore whitespace
 from django.conf import settings
 from django.db.utils import load_backend
 import sqlalchemy.pool as pool
-pool_initialized=False
+
+pool_initialized = False
+
 
 def init_pool():
     """From http://blog.bootstraptoday.com/2012/07/11/django-connection-pooling-using-sqlalchemy-connection-pool/"""
         try:
             backendname = settings.DATABASES['default']['ENGINE']
             backend = load_backend(backendname)
-        
+
             #replace the database object with a proxy.
             backend.Database = pool.manage(backend.Database, pool_size=settings.DB_POOL_SIZE, max_overflow=-1)
-        
+
             backend.DatabaseError = backend.Database.DatabaseError
             backend.IntegrityError = backend.Database.IntegrityError
             logging.info("Connection Pool initialized")
 #Now call init_pool function to initialize the connection pool. No change required in the
 # Django code.
 if settings.USE_DB_CONNECTION_POOLING:
-    init_pool()
+    init_pool()

File ahgl/about/models.py

View file
  • Ignore whitespace
-from django.db import models
-
-# Create your models here.

File ahgl/about/urls.py

View file
  • Ignore whitespace
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import patterns, url
 from django.views.generic.simple import direct_to_template
 
 

File ahgl/auth_backends.py

View file
  • Ignore whitespace
 from account.auth_backends import HybridAuthenticationBackend
 from phileo.auth_backends import CanLikeBackend
 
+
 class FbLikableBackend(CanLikeBackend, FacebookBackend):
     pass
 
+
 class HybridLikeableBackend(CanLikeBackend, HybridAuthenticationBackend):
-    pass
+    pass

File ahgl/env.py

View file
  • Ignore whitespace
 def setup_environ(dunder_file=None, project_path=None, relative_project_path=None, settings_path=None):
     assert not (dunder_file and project_path), ("You must not specify both "
         "__file__ and project_path")
-    
+
     if dunder_file is not None:
         file_path = os.path.abspath(os.path.dirname(dunder_file))
         if relative_project_path is not None:
             project_path = os.path.abspath(os.path.join(file_path, *relative_project_path))
         else:
             project_path = file_path
-    
+
     # the basename must be the project name and importable.
     project_name = os.path.basename(project_path)
-    
+
     # setup Django correctly (the hard-coding of settings is only temporary.
     # carljm's proposal will remove that)
     if settings_path is None:
             os.environ["DJANGO_SETTINGS_MODULE"] = "%s.settings" % project_name
     else:
         os.environ["DJANGO_SETTINGS_MODULE"] = settings_path
-    
+
     # ensure the importablity of project
     sys.path.append(os.path.join(project_path, os.pardir))
     import_module(project_name)
     sys.path.pop()
-    
+
     # Pinax adds an app directory for users as a reliable location for
     # Django apps
-    sys.path.insert(0, os.path.join(project_path, "apps"))
+    sys.path.insert(0, os.path.join(project_path, "apps"))

File ahgl/profiles/__init__.py

View file
  • Ignore whitespace
-
 RACES = (
-         ("T", "Terran"),
-         ("P", "Protoss"),
-         ("Z", "Zerg"),
-         ("R", "Random"),
-         )
+    ("T", "Terran"),
+    ("P", "Protoss"),
+    ("Z", "Zerg"),
+    ("R", "Random"),
+)

File ahgl/profiles/admin.py

View file
  • Ignore whitespace
 from .models import Profile, Team, Charity, TeamMembership, Caster
 from .fields import HTMLField
 
+
 class TeamAdmin(admin.ModelAdmin):
     prepopulated_fields = {"slug": ("name",)}
-    list_display = ('__unicode__', 'tournament','seed','status','paid','charity',)
-    list_filter = ('tournament','status','charity','paid',)
+    list_display = ('__unicode__', 'tournament', 'seed', 'status', 'paid', 'charity',)
+    list_filter = ('tournament', 'status', 'charity', 'paid',)
     ordering = ('tournament',)
-    list_editable = ('seed','paid',)
-   
+    list_editable = ('seed', 'paid',)
+
+
 class TeamMembershipAdminInline(admin.TabularInline):
     model = TeamMembership
     extra = 1
     exclude = ('questions_answers',)
     formfield_overrides = {
-        HTMLField: {'widget': TinyMCE(mce_attrs={'theme':'advanced'})},
+        HTMLField: {'widget': TinyMCE(mce_attrs={'theme': 'advanced'})},
     }
+
+
 class TeamMembershipAdmin(admin.ModelAdmin):
-    list_display = ('__unicode__', 'active','captain',)
-    list_filter = ('team','race','champion','captain',)
+    list_display = ('__unicode__', 'active', 'captain',)
+    list_filter = ('team', 'race', 'champion', 'captain',)
     search_fields = ('char_name',)
     formfield_overrides = {
-        HTMLField: {'widget': TinyMCE(mce_attrs={'theme':'advanced'})},
+        HTMLField: {'widget': TinyMCE(mce_attrs={'theme': 'advanced'})},
     }
 
+
 class ProfileAdmin(admin.ModelAdmin):
     list_display = ('__unicode__', )
     list_filter = ('teams',)
-    search_fields = ('name','team_membership__char_name','user__username',)
+    search_fields = ('name', 'team_membership__char_name', 'user__username',)
     inlines = (TeamMembershipAdminInline,)
-    
+
+
 class CasterAdmin(admin.ModelAdmin):
     list_display = ('user', )
-    actions = ['reset_votes',]
-    
+    actions = ['reset_votes']
+
     def reset_votes(self, request, queryset):
         for caster in queryset.all():
             Like.objects.filter(
-                                receiver_content_type=ContentType.objects.get_for_model(caster),
-                                receiver_object_id=caster.pk
-                                ).delete()
-        self.message_user(request, "Votes successfully deleted.".format(rows_deleted))
-
+                receiver_content_type=ContentType.objects.get_for_model(caster),
+                receiver_object_id=caster.pk).delete()
+        # Commented out because `rows_deleted` doesn't exist.
+        # self.message_user(request, "Votes successfully deleted.".format(rows_deleted))
 
 admin.site.register(TeamMembership, TeamMembershipAdmin)
 admin.site.register(Profile, ProfileAdmin)

File ahgl/profiles/fields.py

View file
  • Ignore whitespace
 
 from tinymce.widgets import TinyMCE
 
+
 class HTMLField(models.TextField):
     """This stores HTML content to be displayed raw to the user.
     The content is cleaned using bleach to restrict the set of HTML used.
     The TinyMCE widget is used for form editing."""
     __metaclass__ = models.SubfieldBase
-    
+
     def __init__(self, tags=None, attributes=None, *args, **kwargs):
         self.tags = tags
         self.attributes = attributes
             else:
                 self.attributes = []
         return super(HTMLField, self).__init__(*args, **kwargs)
-    
+
     def formfield(self, **kwargs):
         defaults = {'widget': TinyMCE()}
         defaults.update(kwargs)
         return super(HTMLField, self).formfield(**defaults)
-    
+
     def to_python(self, value):
         value = super(HTMLField, self).to_python(value)
         value = bleach.clean(value, tags=self.tags, attributes=self.attributes, strip=True)
         value = bleach.linkify(value)
         return mark_safe(value)
-    
+
 try:
     from south.modelsinspector import add_introspection_rules
-    rules = [
-      (
+    rules = [(
         (HTMLField,),
         [],
         {
             "tags": ["tags", {"default": None}],
             "attributes": ["attributes", {"default": None}],
         },
-      )
-    ]
+    )]
     add_introspection_rules(rules, ["^profiles\.fields\.HTMLField"])
 except ImportError:
     pass

File ahgl/profiles/management/commands/clear_emails.py

View file
  • Ignore whitespace
 # coding=utf8
 from __future__ import print_function
 
-from django.core.management.base import BaseCommand, CommandError
+from django.core.management.base import BaseCommand
 
 from django.contrib.auth.models import User
 
+
 class Command(BaseCommand):
     args = ''
     help = 'Clears all emails from user profiles'
                 user.email = ""
                 user.save()
             except Exception:
-                pass
+                pass

File ahgl/profiles/models.py

View file
  • Ignore whitespace
-import posixpath
 import urllib2
 import logging
 
 from django.core.files.base import ContentFile
-from django.core.files.storage import default_storage
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
 from django.conf import settings
-from django.utils.safestring import mark_safe
-from django.template.defaultfilters import escape
 from django.dispatch import receiver
-from django.db.models.signals import post_save
 from django.contrib.auth.models import User
 from django.db import IntegrityError, transaction
 from django.template.defaultfilters import slugify
 
 logger = logging.getLogger(__name__)
 
+
 class Profile(PybbProfile):
     user = models.ForeignKey(User, verbose_name=_("user"), related_name="profile")
     name = models.CharField(_("name"), max_length=50)
-    slug = models.SlugField(max_length=50, editable=False, unique=True) # TODO: make autogenerated slug field that points to the field it gets its sluggification from
+    slug = models.SlugField(max_length=50, editable=False, unique=True)  # TODO: make autogenerated slug field that points to the field it gets its sluggification from
     photo = ImageField(upload_to='profile_photos', null=True, blank=True, help_text=u"Must be 352 x 450 pixels")
     custom_thumb = ImageField(upload_to='profile_custom_thumb_photos', null=True, blank=True, help_text=u"Must be 150 x 170 pixels")
     #about = models.TextField(_("about"), null=True, blank=True)
 
     #company data
     title = models.CharField(max_length=70, blank=True)
-    
+
     @property
     def avatar(self):
         return self.thumbnail()
-    
+
     @property
     def thumbnail(self):
         return self.custom_thumb or self.photo
-    
+
     @property
     def profile_slug(self):
         return self.slug
 
-    def is_active(self, tournament=None): #TODO: make this check if they are active in that particular tournament
+    def is_active(self, tournament=None):  # TODO: make this check if they are active in that particular tournament
         return self.user.is_superuser or self.teams.filter(tournament__status='A').count() > 0
-    
+
     def is_captain(self):
         return self.team_membership.filter(captain=True, team__tournament__status='A').count() > 0
-    
+
     def active_teams(self):
         return self.teams.filter(tournament__status='A').select_related('tournament')
-    
+
     def memberships(self):
         return self.team_membership.select_related('team__tournament')
 
     @property
     def wins(self):
         return Game.objects.filter(winner__profile=self, match__published=True).count()
+
     @property
     def losses(self):
         return Game.objects.filter(loser__profile=self, match__published=True).count()
-    
+
     def __unicode__(self):
         return self.name or self.user.username
-    
+
     @models.permalink
     def get_absolute_url(self, group=None):
-        return ('profile_detail', (), {'slug': self.slug,
-                                       }
-                )
+        return ('profile_detail', (), {'slug': self.slug})
 
     @classmethod
     def get_form(cls):
         else:
             return super(Profile, self).save(*args, **kwargs)
 
+
 class TeamMembership(models.Model):
     """All team specific profile data goes here"""
     #M2M data
     char_name = models.CharField(max_length=20)
     active = models.BooleanField(default=True)
     captain = models.BooleanField(default=False)
-    questions_answers = HTMLField(tags=['ol','ul','li', 'strong', 'em', 'p'], blank=True, default="""<ol><li>
+    questions_answers = HTMLField(tags=['ol', 'ul', 'li', 'strong', 'em', 'p'], blank=True, default="""<ol><li>
 <p>Why did you choose this race/champion?</p>
 <p>-</p>
 </li>
 </li>
 </ol>""")
     game_profile = models.URLField(null=True, blank=True)
-    
+
     #starcraft data
     char_code = models.PositiveSmallIntegerField(null=True, blank=True)
     race = models.CharField(max_length=1, choices=RACES, null=True, blank=True)
-    
+
     #league of legends data
     champion = models.CharField(max_length=60, blank=True)
 
     @property
     def photo(self):
         return self.profile.photo
+
     @property
     def thumbnail(self):
         return self.profile.thumbnail
+
     @property
     def wins(self):
         return self.game_wins.filter(match__published=True).count()
+
     @property
     def losses(self):
         return self.game_losses.filter(match__published=True).count()
 
     @models.permalink
     def get_absolute_url(self, group=None):
-        return ('player_profile', (), {'tournament': self.team.tournament_id,
-                                       'team': self.team.slug,
-                                       'profile': self.profile.slug,
-                                       }
-                )
+        return ('player_profile', (), {
+            'tournament': self.team.tournament_id,
+            'team': self.team.slug,
+            'profile': self.profile.slug,
+        })
 
     def __unicode__(self):
         return self.char_name
         unique_together = (('team', 'profile'),)
         ordering = ('-active', '-captain', 'char_name',)
 
+
 class Team(models.Model):
     """Per Tournament"""
     name = models.CharField(_("company name"), max_length=50)
     members = models.ManyToManyField('Profile', null=True, blank=True, related_name='teams', through=TeamMembership)
     tournament = models.ForeignKey('tournaments.Tournament', related_name='teams', db_index=True)
     karma = models.IntegerField(default=0)
-    
+
     wins = models.IntegerField(default=0, editable=False)
     losses = models.IntegerField(default=0, editable=False)
     tiebreaker = models.IntegerField(default=0, editable=False)
-    
+
     seed = models.IntegerField(default=0)
-    
-    status = models.CharField(max_length=1, choices=(('R', 'Registering'),('W', 'Awaiting Approval'), ('A', 'Accepted'),('F', 'Finalized')), default='R')
+
+    status = models.CharField(max_length=1, choices=(('R', 'Registering'), ('W', 'Awaiting Approval'), ('A', 'Accepted'), ('F', 'Finalized')), default='R')
     paid = models.BooleanField(default=False)
-    
+
     def update_stats(self):
         self.wins = self.match_wins.filter(published=True).count()
         self.losses = self.match_losses.filter(published=True).count()
     @property
     def thumbnail(self):
         return self.photo
-    
+
     @property
     def membership_queryset(self):
         self._team_membership_queryset = getattr(self, '_team_membership_queryset', None) or self.team_membership.select_related('profile').extra(select={'lower_char_name': 'lower(char_name)'}).order_by('-active', '-captain', 'lower_char_name')
-        return self._team_membership_queryset        
+        return self._team_membership_queryset
+
     @property
     def captains(self):
         return [membership for membership in self.membership_queryset if membership.captain]
-    
+
     def __unicode__(self):
         return u" : ".join((self.name, self.tournament.name))
-    
+
     @models.permalink
     def get_absolute_url(self):
-        return ('team_page', (), {'tournament': self.tournament_id,
-                                  'slug': self.slug,
-                                  }
-                )
-    
+        return ('team_page', (), {
+            'tournament': self.tournament_id,
+            'slug': self.slug,
+        })
+
     class Meta:
-        unique_together = (('name','tournament'),('slug', 'tournament'),)
+        unique_together = (('name', 'tournament'), ('slug', 'tournament'),)
         ordering = ('name',)
 
+
 class Charity(models.Model):
     name = models.CharField(_("name"), max_length=60)
     desc = models.TextField(blank=True)
     link = models.URLField(blank=True)
     logo = ImageField(upload_to='charity_logos', null=True, blank=True)
-    
+
     def __unicode__(self):
         return self.name
-    
+
     class Meta:
         ordering = ('name',)
         verbose_name_plural = "charities"
-        
+
+
 class Caster(models.Model):
     user = models.ForeignKey(User, verbose_name=_("user"), related_name="caster_profile")
     tournament = models.ForeignKey('tournaments.Tournament', related_name="casters")
     photo = ImageField(upload_to='caster_photos', null=True, blank=True, help_text=u"Must be 352 x 450 pixels")
     featured_match = models.ForeignKey('tournaments.Match', null=True, blank=True, related_name="casters")
     active = models.BooleanField(default=True)
-    
+
     def __unicode__(self):
         return u" ".join((unicode(self.tournament), unicode(self.user)))
 
+
 @receiver(socialauth_registered, sender=FacebookBackend, dispatch_uid="tournaments_facebook_extra_values")
 def facebook_extra_values(sender, user, response, details, **kwargs):
     for name, value in details.iteritems():
             continue
         if value and value != getattr(user, name, None):
             setattr(user, name, value)
-    
+
     profile = user.get_profile()
     profile.name = response.get('name')
     if not profile.photo:
             # Facebook default image check
             if sender.name == 'facebook' and 'image/gif' in str(content.info()):
                 return
-     
+
             filename = user.username + "_profile" + '.' + content.headers.subtype
             profile.photo.save(filename, ContentFile(content.read()))
         except IOError, e:
         account.language = response.get('locale').split("_")[0]
         tz_offset = int(response.get('timezone'))
         tz_joiner = "" if tz_offset < 0 else "+"
-        account.timezone = coerce_timezone_value(tz_joiner.join(("Etc/GMT",str(tz_offset))))
+        account.timezone = coerce_timezone_value(tz_joiner.join(("Etc/GMT", str(tz_offset))))
         account.full_clean()
     except Exception:
         pass

File ahgl/profiles/pipeline/user.py

View file
  • Ignore whitespace
 
 logger = logging.getLogger(__name__)
 
+
 def get_username(details, response, user=None, *args, **kwargs):
     """Return an username for new user. Return current user username
     if user was given.
             if not Profile.objects.filter(user=user).count():
                 profile.user = user
                 profile.save()
-        
+
     if not user:
         user = User.objects.create_user(username=username, email=email)
     return {

File ahgl/profiles/views.py

View file
  • Ignore whitespace
 from .models import Team, TeamMembership, Profile, Caster
 from tournaments.models import TournamentRound, Tournament
 
+
 class TournamentSlugContextView(object):
     def get_context_data(self, **kwargs):
         context = super(TournamentSlugContextView, self).get_context_data(**kwargs)
             pass"""
         return context
 
+
 class TeamDetailView(TournamentSlugContextView, DetailView):
     def get_context_data(self, **kwargs):
         context = super(TeamDetailView, self).get_context_data(**kwargs)
-        context['is_captain'] = self.request.user.is_authenticated() and any((captain.profile.user_id==self.request.user.id for captain in self.object.captains))
+        context['is_captain'] = self.request.user.is_authenticated() and any((captain.profile.user_id == self.request.user.id for captain in self.object.captains))
         return context
-        
+
     def get_queryset(self):
         return Team.objects.filter(tournament=self.kwargs['tournament']).select_related('charity')
-    
+
+
 class TeamUpdateView(ObjectPermissionsCheckMixin, TournamentSlugContextView, UpdateView):
     def get_queryset(self):
         return Team.objects.filter(tournament=self.kwargs['tournament']).select_related('charity')
-    
+
     def get_form_class(self):
         view = self
+
         class UpdateForm(ModelForm):
             def __init__(self, *args, **kwargs):
                 super(UpdateForm, self).__init__(*args, **kwargs)
                     for key, field in self.fields.iteritems():
                         if key != 'approval':
                             field.required = True
+
             def save(self, *args, **kwargs):
                 if view.request.POST.get('submit') == 'approval':
                     self.instance.status = "W"
                 super(UpdateForm, self).save(*args, **kwargs)
-                
+
             class Meta:
                 model = Team
-                exclude = ('slug','tournament','rank','seed','members','status','paid','karma',)
+                exclude = ('slug', 'tournament', 'rank', 'seed', 'members', 'status', 'paid', 'karma',)
         return UpdateForm
-    
+
     def get_success_url(self):
         return reverse("team_page", kwargs=self.kwargs)
 
     def check_permissions(self):
         if not self.request.user.is_superuser and not self.object.team_membership.filter(captain=True, profile__user=self.request.user).count():
             return HttpResponseForbidden("You are not captain of this team.")
-        
+
     @method_decorator(login_required)
     def dispatch(self, *args, **kwargs):
         return super(TeamUpdateView, self).dispatch(*args, **kwargs)
 
+
 class TeamCreateView(TournamentSlugContextView, CreateView):
     model = Team
-    
+
     def get_form_class(self):
         view = self
+
         class TeamCreateForm(ModelForm):
             #duplicate = forms.ModelChoiceField(queryset=Team.objects.filter(team_membership__profile__user=view.request.user), required=False)
             char_name = forms.CharField(max_length=TeamMembership._meta.get_field('char_name').max_length, required=True, label="Your character name", help_text=u"or Summoner name")
+
             class Meta:
                 model = Team
-                exclude=('tournament','rank','seed','members','slug','status','approval','paid','karma',)
-            """def clean(self):
-                if self.cleaned_data.get('duplicate'):
-                    dup = self.cleaned_data.get('duplicate')
-                    copy = ('name', 'slug', 'photo', 'charity', 'motto')
-                    for field in copy:
-                        if not self.cleaned_data.get(field):
-                            self.cleaned_data[field] = getattr(dup, field)
-                return super(TeamCreateForm, self).clean()"""
+                exclude = ('tournament', 'rank', 'seed', 'members', 'slug', 'status', 'approval', 'paid', 'karma',)
+
+            # def clean(self):
+            #     if self.cleaned_data.get('duplicate'):
+            #         dup = self.cleaned_data.get('duplicate')
+            #         copy = ('name', 'slug', 'photo', 'charity', 'motto')
+            #         for field in copy:
+            #             if not self.cleaned_data.get(field):
+            #                 self.cleaned_data[field] = getattr(dup, field)
+            #     return super(TeamCreateForm, self).clean()
+
             def save(self, *args, **kwargs):
                 self.instance.tournament = view.tournament
                 view.slug = self.instance.slug = slugify(self.cleaned_data['name'])
                     membership = TeamMembership(team=self.instance, profile=view.request.user.get_profile(), char_name=self.cleaned_data['char_name'], active=True, captain=True)
                     membership.save()
         return TeamCreateForm
-    
+
     def get_success_url(self):
-        return reverse("team_page", kwargs={"tournament":self.kwargs['tournament'], "slug":self.slug})
-    
+        return reverse("team_page", kwargs={"tournament": self.kwargs['tournament'], "slug": self.slug})
+
     @method_decorator(login_required)
     def dispatch(self, request, *args, **kwargs):
         self.tournament = get_object_or_404(Tournament, slug=kwargs['tournament'])
         if self.tournament.status != "S":
             return HttpResponseForbidden("That tournament is not open for signups at this time.")
         return super(TeamCreateView, self).dispatch(request, *args, **kwargs)
-    
+
+
 class TeamListView(TournamentSlugContextView, ListView):
     def get_queryset(self):
-        return Team.objects.filter(tournament=self.kwargs['tournament']).only('name','slug','photo','tournament')
-    
+        return Team.objects.filter(tournament=self.kwargs['tournament']).only('name', 'slug', 'photo', 'tournament')
+
+
 class StandingsView(TournamentSlugContextView, ListView):
     def get_context_data(self, **kwargs):
         ctx = super(StandingsView, self).get_context_data(**kwargs)
-        ctx["show_points"] = get_object_or_404(Tournament.objects.only('structure'), pk=self.kwargs['tournament']).structure=="I"
+        ctx["show_points"] = get_object_or_404(Tournament.objects.only('structure'), pk=self.kwargs['tournament']).structure == "I"
         return ctx
-    
+
     def get_queryset(self):
         return TournamentRound.objects.filter(tournament=self.kwargs['tournament'], published=True)
 
     def get_template_names(self):
         return "profiles/standings.html"
 
+
 class TeamMembershipCreateView(CreateView):
     model = TeamMembership
     template_name = "profiles/membership_form.html"
     context_object_name = "membership"
+
     def get_form_class(self):
         view = self
+
         class MembershipCreateForm(ModelForm):
             team = forms.ModelChoiceField(queryset=Team.objects.filter(team_membership__profile__user=view.request.user))
             profile = forms.ModelChoiceField(queryset=Profile.objects.filter(slug=self.kwargs['slug']), initial=view.profile, widget=forms.HiddenInput())
+
             class Meta:
                 model = TeamMembership
-                fields = ('char_name','team','profile')
+                fields = ('char_name', 'team', 'profile')
+
             def save(self, *args, **kwargs):
                 self.cleaned_data['profile'] = view.profile
                 return super(MembershipCreateForm, self).save(*args, **kwargs)
         return MembershipCreateForm
+
     @method_decorator(login_required)
     def dispatch(self, request, *args, **kwargs):
         self.profile = get_object_or_404(Profile, slug=kwargs['slug'])
         return super(TeamMembershipCreateView, self).dispatch(request, *args, **kwargs)
+
+
 class TeamMembershipUpdateView(ObjectPermissionsCheckMixin, UpdateView):
     template_name = "idios/profile_edit.html"
     template_name_ajax = "idios/profile_edit_ajax.html"
     template_name_ajax_success = "idios/profile_edit_ajax_success.html"
     context_object_name = "profile"
     model = TeamMembership
-    
+
     def get_template_names(self):
         if self.request.is_ajax():
             return [self.template_name_ajax]
         else:
             return [self.template_name]
+
     def get_context_data(self, **kwargs):
         ctx = super(TeamMembershipUpdateView, self).get_context_data(**kwargs)
         ctx["profile_form"] = ctx["form"]
         if not self.captain_user:
             exclude += ["captain", "active"]
         return model_forms.modelform_factory(TeamMembership, exclude=exclude)
-    
+
     def form_valid(self, form):
         self.object = form.save()
         if self.request.is_ajax():
             return HttpResponse(json.dumps(data), content_type="application/json")
         else:
             return HttpResponseRedirect(self.get_success_url())
-    
+
     def form_invalid(self, form):
         if self.request.is_ajax():
             ctx = RequestContext(self.request, self.get_context_data(form=form))
         self.captain_user = bool(TeamMembership.objects.filter(team=self.object.team, profile__user=self.request.user, captain=True).count())
         if self.object.profile.user != self.request.user and not self.captain_user:
             return HttpResponseForbidden("This is not your membership to edit.")
-        
+
     @method_decorator(login_required)
     def dispatch(self, *args, **kwargs):
         return super(TeamMembershipUpdateView, self).dispatch(*args, **kwargs)
 
+
 class TeamMembershipDeleteView(ObjectPermissionsCheckMixin, DeleteView):
     context_object_name = "profile"
     model = TeamMembership
+
     def get_success_url(self):
-        return reverse("team_page", kwargs={"tournament":self.object.team.tournament.slug, "slug":self.object.team.slug})
+        return reverse("team_page", kwargs={"tournament": self.object.team.tournament.slug, "slug": self.object.team.slug})
 
     def check_permissions(self):
         self.captain_user = bool(TeamMembership.objects.filter(team=self.object.team, profile__user=self.request.user, captain=True).count())
         if self.object.profile.user != self.request.user and not self.captain_user:
             return HttpResponseForbidden("This is not your membership to delete.")
-        
+
     @method_decorator(login_required)
     def dispatch(self, *args, **kwargs):
         return super(TeamMembershipDeleteView, self).dispatch(*args, **kwargs)
 
+
 class TeamMembershipView(TournamentSlugContextView, DetailView):
     template_name = "profiles/player_profile.html"
     context_object_name = "membership"
+
     def get_queryset(self):
         return TeamMembership.get(**self.kwargs)
+
     def get_context_data(self, **kwargs):
         ctx = super(TeamMembershipView, self).get_context_data(**kwargs)
         ctx['is_me'] = self.request.user.is_authenticated() and self.request.user.id == self.object.profile.user_id
         return ctx
+
     def get_object(self, queryset=None):
         if queryset is None:
             queryset = self.get_queryset()
                           {'verbose_name': queryset.model._meta.verbose_name})
         return obj
 
+
 class MVPView(TournamentSlugContextView, ListView):
     template_name = "profiles/mvp.html"
     context_object_name = "players"
-    
+
     def get_queryset(self):
-        return TeamMembership.objects.filter(team__tournament=self.kwargs.get('tournament'), game_wins__match__published=True).select_related('team','profile').annotate(win_count=Count('game_wins')).order_by('-win_count')
+        return TeamMembership.objects.filter(team__tournament=self.kwargs.get('tournament'), game_wins__match__published=True).select_related('team', 'profile').annotate(win_count=Count('game_wins')).order_by('-win_count')
+
 
 class MyProfileDetailView(ProfileDetailView):
     def get_object(self):
         except:
             self.kwargs['username'] = slug
             return super(MyProfileDetailView, self).get_object()
-    
+
+
 class CasterListView(ListView):
     template_name = "profiles/casters.html"
     context_object_name = "casters"
+
     def get_queryset(self):
         return Caster.objects.filter(tournament=self.kwargs.get('tournament')).order_by('-active', '?')
-    

File ahgl/settings.py

View file
  • Ignore whitespace
 TEMPLATE_LOADERS = (
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader',
-#     'django.template.loaders.eggs.Loader',
+    # 'django.template.loaders.eggs.Loader',
 )
 
 MIDDLEWARE_CLASSES = [
     "sekizai.context_processors.sekizai",
     "django.core.context_processors.request",
     "django.contrib.messages.context_processors.messages",
-    
+
     "staticfiles.context_processors.static",
-    
+
     "notification.context_processors.notification",
     "django_messages.context_processors.inbox",
-    
+
     #"pybb.context_processors.processor",
-    
+
     #"tournaments.context_processors.tournament",
 ]
 
     "django.contrib.redirects",
     "django.contrib.sites",
 
-  
+
     # theme
     "pinax_theme_bootstrap_account",
     "pinax_theme_bootstrap",
-    
+
     # external
-    "notification", # must be first
+    "notification",  # must be first
     'account',
     "staticfiles",
     "compressor",
     'raven.contrib.django',
     'clear_cache',
     'phileo',
-    
+
     # cms
     'cms',
     'mptt',
     "utils",
 ]
 
-"""FIXTURE_DIRS = [
-    os.path.join(PROJECT_ROOT, "fixtures"),
-]"""
+# FIXTURE_DIRS = [
+#     os.path.join(PROJECT_ROOT, "fixtures"),
+# ]
 
 PAGINATION_INVALID_PAGE_RAISES_404 = True
 
 TINYMCE_DEFAULT_CONFIG = {
     'theme': "simple",
     'custom_undo_redo_levels': 10,
-    'width':"100%",
-    'height':"480",
+    'width': "100%",
+    'height': "480",
 }
 
 MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
 }
 
 #Queryset caching with johnny-cache
-JOHNNY_TABLE_WHITELIST = ['cms_cmsplugin',
-'cms_globalpagepermission',
-'cms_globalpagepermissions_sites',
-'cms_page',
-'cms_page_placeholders',
-'cms_pagemoderator',
-'cms_pagemoderatorstate',
-'cms_pagepermission',
-'cms_pageuser',
-'cms_pageusergroup',
-'cms_placeholder',
-'cms_title',
-'cmsplugin_tournamentpluginmodel',
-'cmsplugin_gamepluginmodel',
-'cmsplugin_file',
-'cmsplugin_googlemap',
-'cmsplugin_link',
-'cmsplugin_picture',
-'cmsplugin_snippetptr',
-'cmsplugin_teaser',
-'cmsplugin_text',
-'cmsplugin_twitterrecententries',
-'cmsplugin_twittersearch',
-'cmsplugin_video',
-'menus_cachekey',
-'snippet_snippet',
-'django_site',
-'auth_group',
-'auth_user_groups',
+JOHNNY_TABLE_WHITELIST = [
+    'cms_cmsplugin',
+    'cms_globalpagepermission',
+    'cms_globalpagepermissions_sites',
+    'cms_page',
+    'cms_page_placeholders',
+    'cms_pagemoderator',
+    'cms_pagemoderatorstate',
+    'cms_pagepermission',
+    'cms_pageuser',
+    'cms_pageusergroup',
+    'cms_placeholder',
+    'cms_title',
+    'cmsplugin_tournamentpluginmodel',
+    'cmsplugin_gamepluginmodel',
+    'cmsplugin_file',
+    'cmsplugin_googlemap',
+    'cmsplugin_link',
+    'cmsplugin_picture',
+    'cmsplugin_snippetptr',
+    'cmsplugin_teaser',
+    'cmsplugin_text',
+    'cmsplugin_twitterrecententries',
+    'cmsplugin_twittersearch',
+    'cmsplugin_video',
+    'menus_cachekey',
+    'snippet_snippet',
+    'django_site',
+    'auth_group',
+    'auth_user_groups',
 ]
 
 CMS_TEMPLATES = (
 
 #PYBB_TEMPLATE = "pybb_base.html"
 
-ALLOWED_TAGS = ['a', 'abbr', 'acronym', 'blockquote', 'br', 'cite', 'code', 'dd', 'del',
-                 'div', 'dl', 'dt', 'em', 'h2', 'h3', 'h4', 'h5', 'i', 'iframe', 'img', 'ins', 'li', 'ol', 'p',
-                 'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'td',
-                 'th', 'tr', 'u', 'ul']
+ALLOWED_TAGS = ['a', 'abbr', 'acronym', 'blockquote', 'br', 'cite', 'code',
+                'dd', 'del', 'div', 'dl', 'dt', 'em', 'h2', 'h3', 'h4', 'h5',
+                'i', 'iframe', 'img', 'ins', 'li', 'ol', 'p', 'pre', 'q',
+                'small', 'span', 'strong', 'sub', 'sup', 'table', 'td', 'th',
+                'tr', 'u', 'ul']
 ALLOWED_ATTRIBUTES = {
-                'a'         : ['href', 'rel', 'target', 'title', 'data-toggle', 'class'],
-                'blockquote': ['cite'],
-                'q'         : ['cite'],
-                'img'       : ['src', 'alt', 'title', 'style'],
-                'iframe'    : ['src', 'width', 'height', 'frameborder', 'allowfullscreen'],
-                'div'       : ['class', 'id', 'style',],
-                'span'      : ['class',],
-                'p'         : ['style'],
-                'table'     : ['class',],
-                'td'        : ['colspan',],
-                'th'        : ['colspan',],
-                'ul'        : ['class',],
-                'li'        : ['class',],
-             }
-ALLOWED_STYLES = ['float','text-align','width','height',]
+    'a': ['href', 'rel', 'target', 'title', 'data-toggle', 'class'],
+    'blockquote': ['cite'],
+    'q': ['cite'],
+    'img': ['src', 'alt', 'title', 'style'],
+    'iframe': ['src', 'width', 'height', 'frameborder', 'allowfullscreen'],
+    'div': ['class', 'id', 'style'],
+    'span': ['class'],
+    'p': ['style'],
+    'table': ['class'],
+    'td': ['colspan'],
+    'th': ['colspan'],
+    'ul': ['class'],
+    'li': ['class'],
+}
+ALLOWED_STYLES = ['float', 'text-align', 'width', 'height']
 ALLOWED_CLASSES = ['accordion-group', 'accordion-heading', 'accordion-toggle',
                    'accordion-body', 'accordion-inner', 'clearfix', 'collapse',
                    'bracket', 'bracket-round', 'bracket-item', 'winner', 'team',
-                   'seed', 'score', 'team_name', 'team-link', 'thumbnail', 'caption', 'thumbnails',
-                   'pull-right', 'pull-left', 'table', 'table-striped', 'table-bordered', 'table-hover',
-                   'table-condensed', 'error', 'success', 'warning', 'info', 'unstyled',
-                   'span1', 'span2', 'span3', 'span4', 'span5', 'span6', 'span7', 'span8',
-                   ]
+                   'seed', 'score', 'team_name', 'team-link', 'thumbnail',
+                   'caption', 'thumbnails', 'pull-right', 'pull-left', 'table',
+                   'table-striped', 'table-bordered', 'table-hover',
+                   'table-condensed', 'error', 'success', 'warning', 'info',
+                   'unstyled', 'span1', 'span2', 'span3', 'span4', 'span5',
+                   'span6', 'span7', 'span8', ]
 
 CONTACT_EMAIL = "support@afterhoursgaming.tv"
 
 ]
 
 SOCIAL_AUTH_PIPELINE = (
-                        'social_auth.backends.pipeline.social.social_auth_user',
-                        'social_auth.backends.pipeline.associate.associate_by_email',
-                        'profiles.pipeline.user.get_username',
-                        'profiles.pipeline.user.create_user',
-                        'social_auth.backends.pipeline.social.associate_user',
-                        'social_auth.backends.pipeline.social.load_extra_data',
-                        'social_auth.backends.pipeline.user.update_user_details',
-                        )
+    'social_auth.backends.pipeline.social.social_auth_user',
+    'social_auth.backends.pipeline.associate.associate_by_email',
+    'profiles.pipeline.user.get_username',
+    'profiles.pipeline.user.create_user',
+    'social_auth.backends.pipeline.social.associate_user',
+    'social_auth.backends.pipeline.social.load_extra_data',
+    'social_auth.backends.pipeline.user.update_user_details',
+)
 
 SOCIAL_AUTH_ENABLED_BACKENDS = ('facebook',)
 
-SOCIAL_AUTH_COMPLETE_URL_NAME  = 'socialauth_complete'
+SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
 SOCIAL_AUTH_ASSOCIATE_URL_NAME = 'socialauth_associate_complete'
 
 SOCIAL_AUTH_ASSOCIATE_BY_MAIL = True
 
 FACEBOOK_EXTENDED_PERMISSIONS = ('email',)
 
-LOGIN_URL = "/account/login/" # @@@ any way this can be a url name?
+LOGIN_URL = "/account/login/"  # @@@ any way this can be a url name?
 LOGIN_REDIRECT_URLNAME = "acct_email"
 SOCIAL_AUTH_LOGIN_REDIRECT_URL = "/"
 
     "version": 1,
     "disable_existing_loggers": False,
     "root": {
-        "level" : "WARNING",
+        "level": "WARNING",
         "handlers": ["sentry"],
     },
     "formatters": {
             "level": "ERROR",
             "class": "raven.contrib.django.handlers.SentryHandler",
         },
-        "console":{
+        "console": {
             "level": "INFO",
             "class": "logging.StreamHandler",
             "formatter": "simple"
 # local_settings.py can be used to override environment-specific settings
 # like database and email that differ between development and production.
 try:
-    from local_settings import *
+    from local_settings import *  # noqa
 except ImportError:
     pass

File ahgl/settings_gondor.py

View file
  • Ignore whitespace
 import os
 import urlparse
 
-from .settings import *
+from .settings import *  # noqa
 
 DEBUG = False
 TEMPLATE_DEBUG = DEBUG
     GONDOR_REDIS_HOST = url.hostname
     GONDOR_REDIS_PORT = url.port
     GONDOR_REDIS_PASSWORD = url.password
-    
+
     # Caching
     CACHES = {
         "default": {
             "JOHNNY_CACHE": True,
         },
     }
-    
+
     BROKER_TRANSPORT = "redis"
     BROKER_HOST = GONDOR_REDIS_HOST
     BROKER_PORT = GONDOR_REDIS_PORT
     BROKER_VHOST = "0"
     BROKER_PASSWORD = GONDOR_REDIS_PASSWORD
-    
+
     import djcelery
     djcelery.setup_loader()
     CELERY_RESULT_BACKEND = "redis"
 
 if "GONDOR_HAYSTACK_SOLR_URL" in os.environ:
     if 'HAYSTACK_SEARCH_ENGINE' in locals():
-        del HAYSTACK_SEARCH_ENGINE
+        del HAYSTACK_SEARCH_ENGINE  # noqa
     GONDOR_HAYSTACK_SOLR_URL = os.environ["GONDOR_HAYSTACK_SOLR_URL"]
     HAYSTACK_CONNECTIONS = {
         'default': {
         },
     }
 
-SITE_ID = 1 # set this to match your Sites setup
+SITE_ID = 1  # set this to match your Sites setup
 
 MEDIA_ROOT = os.path.join(os.environ["GONDOR_DATA_DIR"], "site_media", "media")
 STATIC_ROOT = os.path.join(os.environ["GONDOR_DATA_DIR"], "site_media", "static")
 
-MEDIA_URL = "/site_media/media/" # make sure this maps inside of a static_urls URL
-STATIC_URL = "/site_media/static/" # make sure this maps inside of a static_urls URL
+MEDIA_URL = "/site_media/media/"  # make sure this maps inside of a static_urls URL
+STATIC_URL = "/site_media/static/"  # make sure this maps inside of a static_urls URL
 MEDIA_URL = os.environ.get('MEDIA_URL', MEDIA_URL)
 STATIC_URL = os.environ.get('STATIC_URL', STATIC_URL)
 ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/"

File ahgl/startup.py

View file
  • Ignore whitespace
-import copy
-
 from django.conf import settings
 from django.utils.importlib import import_module
 from django.utils.module_loading import module_has_submodule
 
 
 def run():
-    autoload(["receivers"])
+    autoload(["receivers"])

File ahgl/tournaments/admin.py

View file
  • Ignore whitespace
-from django.utils.functional import curry
 from django.contrib import admin
-from django import forms
 from django.conf.urls.defaults import patterns, url
 from django.db import transaction
 from django.db.models.fields.related import RelatedField
 from django.utils import timezone
 
 from .views import NewTournamentRoundView
-from .models import Tournament, TournamentRound, Map, Match, Game, TeamRoundMembership
-from profiles.models import Team, Profile, TeamMembership
+from .models import Tournament, TournamentRound, Map, Match, Game
+from profiles.models import Team, TeamMembership
 
 from .tasks import update_round_stats
 import settings
 
+
 class TournamentRoundInline(admin.TabularInline):
     model = TournamentRound
-    
+
     def get_formset(self, request, obj=None, **kwargs):
         self.parent = obj
         return super(TournamentRoundInline, self).get_formset(request, obj=obj, **kwargs)
             request.team_queryset = kwargs["queryset"] = queryset.only('name')
         return super(TournamentRoundInline, self).formfield_for_manytomany(db_field, request, **kwargs)
 
+
 class TournamentAdmin(admin.ModelAdmin):
     prepopulated_fields = {"slug": ("name",)}
     list_display = ('__unicode__', 'status',)
     list_filter = ('status',)
     inlines = (TournamentRoundInline,)
-    
+
     def get_form(self, request, obj=None, **kwargs):
         self.obj = obj
         return super(TournamentAdmin, self).get_form(request, obj, **kwargs)
-    
+
     @transaction.commit_manually
     def save_model(self, request, obj, form, change):
         try:
             transaction.commit()
             update_round_stats.delay(obj.pk)
             if getattr(settings, "CELERY_ALWAYS_EAGER", False) is True:
-                transaction.commit() # must commit if running in eager task mode
+                transaction.commit()  # must commit if running in eager task mode
 
     def get_urls(self):
         urls = super(TournamentAdmin, self).get_urls()
         )
         return my_urls + urls
 
+
 class GameInline(admin.TabularInline):
     model = Game
-    extra=1
-    
-    team_field_removals = set(('home_player','away_player','home_race','away_race','winner','replay',))
+    extra = 1
+
+    team_field_removals = set(('home_player', 'away_player', 'home_race', 'away_race', 'winner', 'replay',))
     individual_field_removals = set(('winner_team',))
+
     def get_formset(self, request, obj=None, **kwargs):
         self.parent = obj
         if obj:
-            if obj.structure=="I":
+            if obj.structure == "I":
                 self.exclude = self.individual_field_removals
-            elif obj.structure=="T":
+            elif obj.structure == "T":
                 self.exclude = self.team_field_removals
         return super(GameInline, self).get_formset(request, obj=obj, **kwargs)
+
     def formfield_for_foreignkey(self, db_field, request, **kwargs):
         if "player" in db_field.name or db_field.name == "winner":
             if hasattr(request, "membership_queryset"):
         cache_field("team", Team.objects.filter(tournament=self.parent.tournament_id) if self.parent else Team.objects.all(), db_field, request, kwargs)
         cache_field("map", self.parent.tournament.map_pool.all() if self.parent else Map.objects.all(), db_field, request, kwargs)
         return super(GameInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
-    
+
     def queryset(self, request):
         queryset = super(GameInline, self).queryset(request) \
                                           .select_related('home_player', 'away_player')
         if request.method.lower() == "GET":
-            only = ['home_player__char_name', 'away_player__char_name','map','winner', 'winner_team']
+            only = ['home_player__char_name', 'away_player__char_name', 'map', 'winner', 'winner_team']
             only += [field.name for field in self.model._meta.fields if field.editable and not isinstance(field, RelatedField)]
             queryset = queryset.only(*only)
         return queryset
 
+
 def cache_field(field_name, queryset, db_field, request, kwargs):
     attr = "_".join((field_name, "queryset"))
     if field_name in db_field.name:
             setattr(request, attr, queryset)
         kwargs['queryset'] = getattr(request, attr)
 
+
 class MatchAdmin(admin.ModelAdmin):
-    list_display = ('name','winner__name', 'creation_date', 'publish_date', 'home_submission_date', 'away_submission_date', 'tournament_round', 'published',)
-    list_filter = ('tournament','home_submitted','away_submitted',)
-    search_fields = ('home_team__name','away_team__name',)
+    list_display = ('name', 'winner__name', 'creation_date', 'publish_date', 'home_submission_date', 'away_submission_date', 'tournament_round', 'published',)
+    list_filter = ('tournament', 'home_submitted', 'away_submitted',)
+    search_fields = ('home_team__name', 'away_team__name',)
     inlines = (GameInline,)
     actions = ['publish_match', 'delete_and_update_stats']
     date_hierarchy = 'creation_date'
-    readonly_fields = ('tournament', 'home_submission_date', 'away_submission_date','referee',)
-    
+    readonly_fields = ('tournament', 'home_submission_date', 'away_submission_date', 'referee',)
+
     def has_add_permission(self, request):
         return False
+
     def get_form(self, request, obj=None, **kwargs):
         self.obj = obj
         return super(MatchAdmin, self).get_form(request, obj=obj, **kwargs)
+
     def formfield_for_foreignkey(self, db_field, request, **kwargs):
         cache_field("team", Team.objects.filter(tournament=self.obj.tournament_id), db_field, request, kwargs)
-        cache_field("tournament_round", TournamentRound.objects.filter(tournament=self.obj.tournament_id).only('order','stage_name'), db_field, request, kwargs)
+        cache_field("tournament_round", TournamentRound.objects.filter(tournament=self.obj.tournament_id).only('order', 'stage_name'), db_field, request, kwargs)
         return super(MatchAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
-    
+
     def queryset(self, request):
         queryset = super(MatchAdmin, self).queryset(request).select_related('tournament', 'home_team', 'away_team', 'winner').prefetch_related('tournament_round') \
                                           .defer('tournament__status', 'tournament__games_per_match')
         return queryset
-    
+
     def publish_match(self, request, queryset):
         rows_updated = queryset.update(published=True, publish_date=timezone.now())
         for match in queryset.all():
             message_bit = "%s match were" % rows_updated
         self.message_user(request, "%s successfully published." % message_bit)
     publish_match.short_description = "Publish matches so they are visible to all users"
+
     def delete_and_update_stats(self, request, queryset):
         ret = delete_selected(self, request, queryset)
         if request.POST.get('post'):

File ahgl/tournaments/cms_plugins.py

View file
  • Ignore whitespace
 
 from cms.plugin_base import CMSPluginBase
 from cms.plugin_pool import plugin_pool
-from cms.models.pluginmodel import CMSPlugin
 from django.utils.translation import ugettext_lazy as _
 
 from .models import Tournament, GamePluginModel, TournamentPluginModel, Game
 
 r_tourney_slug = re.compile('^(?P<slug>[\w_-]+)/')
 
+
 def tourney_from_slug(request):
     if not hasattr(request, 'tournament'):
         slug = r_tourney_slug.match(request.path).group('slug')
         request.tournament = Tournament.objects.get(slug=slug).select_related('featured_game__map', 'featured_game__home_player', 'featured_game__away_player')
     return request.tournament
 
+
 class GamePlugin(CMSPluginBase):
     model = GamePluginModel
     name = _("Featured Game")
     def get_form(self, request, obj=None, **kwargs):
         self.obj = obj
         return super(GamePlugin, self).get_form(request, obj, **kwargs)
+
     def formfield_for_foreignkey(self, db_field, request, **kwargs):
         if db_field.name == "game":
             kwargs["queryset"] = Game.objects.filter(match__published=True, winner_team__isnull=False, match__tournament=getattr(self.obj, 'tournament', None)) \
         return context
 plugin_pool.register_plugin(GamePlugin)
 
+
 class RandomTeamsPlugin(CMSPluginBase):
     model = TournamentPluginModel
     name = _("Random Teams")
         return context
 plugin_pool.register_plugin(RandomTeamsPlugin)
 
+
 class TournamentNavPlugin(CMSPluginBase):
     model = TournamentPluginModel
     name = _("Tournament Navigation")

File ahgl/tournaments/context_processors.py

View file
  • Ignore whitespace
 
 re_tourney_matcher = re.compile(r'^/(?P<tournament>[\w_-]+)/')
 
+
 def tournament(request):
-    context = {'tournament_slug':re_tourney_matcher.search(request.path).group('tournament')}
+    context = {'tournament_slug': re_tourney_matcher.search(request.path).group('tournament')}
     try:
         context['tournament'] = Tournament.objects.get(slug=context['tournament_slug'])
     except Tournament.DoesNotExist:

File ahgl/tournaments/forms.py

View file
  • Ignore whitespace
 
 from .models import Match
 
+
 class BaseMatchFormSet(BaseModelFormSet):
     def __init__(self, *args, **kwargs):
         super(BaseMatchFormSet, self).__init__(*args, **kwargs)
         self.queryset = Match.objects.none()
+
     def get_queryset(self):
         return Match.objects.none()
+
+
 class MultipleFormSetBase(object):
     def __init__(self, prefix=None, *args, **kwargs):
         if prefix is None:
 
     def __unicode__(self):
         return self.as_table()
-    
+
     def __iter__(self):
         for formset in self.forms:
             yield formset
             #for field in form:
             #    yield field
-    
+
     def is_valid(self):
         return all(form.is_valid() for form in self.forms)
-    
+
     def as_table(self):
         return '\n'.join(form.as_table() for form in self.forms)
-    
+
     def as_ul(self):
         return '\n'.join(form.as_ul() for form in self.forms)
-    
+
     def as_p(self):
         return '\n'.join(form.as_p() for form in self.forms)
-    
+
     def is_multipart(self):
         return any(form.is_multipart() for form in self.forms)
-    
+
     def save(self, commit=True):
         return tuple(form.save(commit) for form in self.forms if hasattr(form, "save"))
     save.alters_data = True

File ahgl/tournaments/management/commands/compute_stats.py

View file
  • Ignore whitespace
         for team in Team.objects.filter(tournament=self.tournament):
             team.update_stats()
         for membership in TeamRoundMembership.objects.filter(tournamentround__tournament=self.tournament):
-            membership.update_stats()
+            membership.update_stats()

File ahgl/tournaments/management/commands/scrape_ahgl.py

View file
  • Ignore whitespace
 import datetime
 from optparse import make_option
 
+from django.contrib.auth.models import User
 from django.core.files.base import ContentFile
 from django.core.exceptions import ValidationError
 from django.core.management.base import BaseCommand, CommandError
 from django.conf import settings
 from django.db.models import Q
 
-from tournaments.models import *
-from profiles.models import *
-from profiles.pipeline.user import *
+from tournaments.models import (Game, Map, Match, TeamRoundMembership,
+                                Tournament, TournamentRound, replay_path)
+from profiles.models import Charity, Profile, Team, TeamMembership
+
 
 class Command(BaseCommand):
     args = '<tournament_slug ahgl_url>'
             dest='admin',
             default=False,
             help='Scrape data from admin page'),
-        )
-    
+    )
+
     first_week_match = datetime.date(2012, 1, 6)
     a_week = datetime.timedelta(weeks=1)
     master_user = User.objects.get(username='master')
     unknown_photo = '/wp-content/themes/AHGL/images/the-unknown.png'
-    
-    _map_map = {u"Xelnaga": "Xel'Naga Caverns", u"Xel’Naga Caverns": "Xel'Naga Caverns", u"Tal’Darim Altar": "Tal'Darim Altar", u"Tal’darim Altar": "Tal'Darim Altar", "Tal'Darim Altar":"Tal'Darim Altar", "The Shattered Temple": "Shattered Temple"}
+
+    _map_map = {
+        u"Xelnaga": "Xel'Naga Caverns",
+        u"Xel’Naga Caverns": "Xel'Naga Caverns",
+        u"Tal’Darim Altar": "Tal'Darim Altar",
+        u"Tal’darim Altar": "Tal'Darim Altar",
+        "Tal'Darim Altar": "Tal'Darim Altar",
+        "The Shattered Temple": "Shattered Temple"
+    }
+
     def coerse_mapname(self, mapname):
         if mapname in self._map_map.keys():
             return self._map_map[mapname]
             membership = TeamMembership(team=team, profile=profile, char_name=char_name, active=False)
             membership.save()
             return profile, membership
-            
-        
+
         if "Player not found in database" in tostring(member_d):
             print("Player not found...skipping", file=self.stdout)
             return
             profile.photo.save(filename, ContentFile(urllib2.urlopen(member_photo_url).read()))
         if info_ps[3].text:
             profile.title = info_ps[3].text
-        if info_ps[-1].text: # deal with blank race
+        if info_ps[-1].text:  # deal with blank race
             if info_h3s[-1].text.strip().lower() == "champion":
                 membership.champion = info_ps[-1].text.strip()
             else:
             profile.save()
             membership.save()
         return profile, membership
+
     def load_team(self, team_url, team_name):
         team_d = self.visit_url(team_url)
-       
+
         # load team data
-        team, created = Team.objects.get_or_create(tournament=self.tournament, name=team_name, slug=slugify(team_name), defaults={'rank':1})
+        team, created = Team.objects.get_or_create(tournament=self.tournament, name=team_name, slug=slugify(team_name), defaults={'rank': 1})
         print(created, file=self.stdout)
         photo_url = team_d.cssselect('.content-section-1 img')[0].get('src')
         filename = slugify(team_name) + posixpath.splitext(photo_url)[1]
         team.photo.save(filename, ContentFile(urllib2.urlopen(photo_url).read()))
-        
+
         charity_p = team_d.cssselect('.content-section-3 p')[0 if self.tournament.slug == "starcraft-2-season-1" else 1]
         charity_name = charity_p.cssselect('a')[0].text
         charity, created = Charity.objects.get_or_create(name=charity_name)
         charity.link = charity_p.cssselect('a')[0].get('href')
         if not charity.desc:
             print("charity desc")
-            charity.desc = charity_p.text_content().strip()[2:] #"".join(list(charity_p.itertext())[1:])
+            charity.desc = charity_p.text_content().strip()[2:]  # "".join(list(charity_p.itertext())[1:])
         if not charity.logo:
             try:
                 charity_photo_url = team_d.cssselect('.content-section-4 img')[0].get('src')
         team.full_clean()
         team.save()
         return team
+
     def find_round(self, home_team, away_team, creation_date):
         for round in TournamentRound.objects.filter(teams__pk=home_team.pk).filter(teams__pk=away_team.pk).order_by('stage_order'):
             previous_matchup_count = round.matches.filter(creation_date__lt=creation_date) \
             if not previous_matchup_count:
                 break
         return round
+
     def load_match(self, match_url, week=None):
         match_d = self.visit_url(match_url)
-        
+
         if not match_d.cssselect('a.first-title'):
             print("Not a real match....skipping", file=self.stderr)
             return
         if week is None:
             week = int(re.search('week[^/]*([\d]+)[^/]*/', match_url).group(1)) - 1
         print("{0} week".format(week), file=self.stdout)
-        creation_date = self.first_week_match + self.a_week*week
+        creation_date = self.first_week_match + self.a_week * week
         round = self.find_round(home_team, away_team, creation_date)
-        match, match_created = Match.objects.get_or_create(home_team=home_team, away_team=away_team, creation_date=creation_date, tournament=self.tournament, defaults={'tournament_round':round})
+        match, match_created = Match.objects.get_or_create(home_team=home_team, away_team=away_team, creation_date=creation_date, tournament=self.tournament, defaults={'tournament_round': round})
         match.published = True
         match.publish_date = match.creation_date + self.a_week + datetime.timedelta(days=5)
         match.home_submitted = True
         match.away_submitted = True
-        
+
         match.save(notify=False)
         # add games
         for order, game_li in enumerate(match_d.cssselect('li.cf'), start=1):
                 map.full_clean()
                 map.save()
             self.tournament.map_pool.add(map)
-            
+
             # Game creation
-            game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map":map})
-            game.map = map # just assure the current coersed version
+            game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map": map})
+            game.map = map  # just assure the current coersed version
             #if game_created:
             #    print("Created game {order}".format(order=order), file=self.stdout)
 
-            # only load players if players play individual games            
+            # only load players if players play individual games
             if not self.options['whole_team']:
                 home_player = game_li.cssselect('.video-player-link-container h3')[0].text
                 away_player = game_li.cssselect('.video-player-link-container.last h3')[0].text
                             profile, membership = self.load_player(url, team, char_name)
                             setattr(game, "_".join((member, "player")), membership)
 
-            
             vod = game_li.cssselect('.video-link-container > a.video-link')[0].get('href')
             if vod and not "afterhoursgaming.tv" in vod:
                 game.vod = vod
             replay_a = game_li.cssselect('.video-link-container > p > a')
             if replay_a:
                 self.save_replay(game, replay_a)
-            if game.order==5:
+            if game.order == 5:
                 game.is_ace = True
             game.save()
         match.save(notify=False)
             return TeamMembership.objects.get(team=team, char_name__iexact=char_name), False
         except TeamMembership.DoesNotExist:
             if active:
-                profile, created = Profile(name=char_name, user=self.master_user), True #have to use fake name since admin doesn't have names
+                profile, created = Profile(name=char_name, user=self.master_user), True  # have to use fake name since admin doesn't have names
                 profile.save()
                 membership = TeamMembership(team=team, profile=profile, char_name=char_name)
                 print("Creating player {0}".format(membership.char_name), file=self.stdout)
 
     re_lineup = re.compile(r"((?P<home_name>[^\.\s]+)(\. ?(?P<home_code>[^\s]+))? +(\([^\)]+\) )?\((?P<home_race>[\w])\))? \< (?P<map>[^\>]+) \> (\((?P<away_race>[\w])\) (?P<away_name>[^\.]+)(\.(?P<away_code>[^\s]+))?)?")
     re_captain = re.compile(r"(?P<name>[^,]+), (?P<email>[^@]+@[^\.]+\.[^,]+), (?P<char_name>[^\.]+)\.(?P<char_code>[\d]+)")
+
     def load_lineup(self, lineup_url):
         lineup_d = self.visit_url(lineup_url)
         week = int(lineup_d.cssselect("h1")[0].text.strip().rsplit(None, 1)[-1]) - 1
             home_team = Team.objects.get(name=home_team, tournament=self.tournament)
             away_team = Team.objects.get(name=away_team, tournament=self.tournament)
 
-            
-            creation_date = self.first_week_match + self.a_week*week
-            try: # ug, inconsistencies in ordering....
+            creation_date = self.first_week_match + self.a_week * week
+            try:  # ug, inconsistencies in ordering....
                 match = Match.objects.get(home_team=away_team, away_team=home_team, creation_date=creation_date, tournament=self.tournament)
             except Match.DoesNotExist:
                 reverse_order = False
                 round = self.find_round(home_team, away_team, creation_date)
-                match, match_created = Match.objects.get_or_create(home_team=home_team, away_team=away_team, creation_date=creation_date, tournament=self.tournament, defaults={'tournament_round':round})
+                match, match_created = Match.objects.get_or_create(home_team=home_team, away_team=away_team, creation_date=creation_date, tournament=self.tournament, defaults={'tournament_round': round})
                 if match_created:
                     print("Creating new match {0} vs {1}".format(home_team, away_team), file=self.stdout)
                 else:
                 print("Processing match {0} vs {1}".format(home_team, away_team), file=self.stdout)
             match.home_submitted = True
             match.away_submitted = True
-            
+
             maps = []
             for order, game_text in enumerate(matchup_p.itertext(), start=1):
                 game_matcher = self.re_lineup.search(game_text.strip())
                 if map_created:
                     print("{0} map not found...creating".format(map_name), file=self.stderr)
                     self.tournament.map_pool.add(map)
-                
-                game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map":map})
-                game.map = map # just assure the current coersed version
+
+                game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map": map})
+                game.map = map  # just assure the current coersed version
                 if game_created:
                     print("  Creating new game {0} {1} {2}".format(home_team.name, map_name, away_team.name), file=self.stdout)
                     match.games.add(game)
-                if game_matcher.group("away_race"): #not ace match, load up player data
+                if game_matcher.group("away_race"):  # not ace match, load up player data
                     p1, p1_created = self.create_membership(team=home_team, char_name=game_matcher.group("home_name"))
                     p2, p2_created = self.create_membership(team=away_team, char_name=game_matcher.group("away_name"))
                     p1race = game_matcher.group("home_race").upper()
                 for match in matches_needing_games:
                     print("Match {0} had no map information...using information from other matches".format(match), file=self.stdout)
                     for order, (map, is_ace) in enumerate(map_pool, start=1):
-                        game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map":map})
+                        game, game_created = Game.objects.get_or_create(match=match, order=order, defaults={"map": map})
                         if game_created:
                             print("Created game on map {0}".format(map.name), file=self.stdout)
                         game.is_ace = is_ace
                 print("No map information was gathered for this week, so deleting all matches.", file=self.stdout)
                 for match in matches_needing_games:
                     match.delete()
-         
+
     re_result = re.compile("\): (?P<home_name>[^\.:\s]+)(\. ?(?P<home_code>[^\s]+))? +(\([^\)]+\) )?\((?P<home_race>[\w])\) (?P<win_ptr>&lt;|&gt;) \((?P<away_race>[\w])\) (?P<away_name>[^\.]+)(\.(?P<away_code>[^\s]+))? +--")
+
     def load_result(self, result_url):
         result_d = self.visit_url(result_url)
         week = int(result_d.cssselect("h1")[0].text.strip().rsplit(None, 1)[-1]) - 1
             home_team, away_team = (s.strip() for s in match_h2.text.split(":")[1].split(" vs "))
             home_team = Team.objects.get(name=home_team, tournament=self.tournament)
             away_team = Team.objects.get(name=away_team, tournament=self.tournament)
-            creation_date = self.first_week_match + self.a_week*week
-            try: # ug, inconsistencies in ordering....
+            creation_date = self.first_week_match + self.a_week * week
+            try:  # ug, inconsistencies in ordering....
                 match = Match.objects.get(home_team=away_team, away_team=home_team, creation_date=creation_date, tournament=self.tournament)
             except Match.DoesNotExist:
                 reverse_order = False
                 try:
                     match = Match.objects.get(home_team=home_team, away_team=away_team, creation_date=creation_date, tournament=self.tournament)
-                except Match.DoesNotExist: # this means we didn't have any map data, so we had deleted the matches
+                except Match.DoesNotExist:  # this means we didn't have any map data, so we had deleted the matches
                     continue
                 print("Processing match {0} vs {1}".format(home_team, away_team), file=self.stdout)
             else:
                             try:
                                 away_player = TeamMembership.objects.get(char_name__iexact=game_matcher.group("away_name").strip().encode('ascii', 'ignore'))
                             except TeamMembership.DoesNotExist:
-                                print(">"+game_matcher.group("away_name").strip().encode('ascii', 'ignore')+"<", "did not match")
+                                print(">" + game_matcher.group("away_name").strip().encode('ascii', 'ignore') + "<", "did not match")
                         else:
                             try:
                                 away_player = TeamMembership.objects.get(char_name__iexact=game_matcher.group("away_name").strip(), char_code=away_code)
                         except TeamMembership.DoesNotExist:
                             kwargs['team'] = home_team
                             home_player = TeamMembership.objects.get(**kwargs)
-                            
+
                     home_race = game_matcher.group("home_race").upper()
                     away_race = game_matcher.group("away_race").upper()
                     if reverse_order:
                     else:
                         print("Unrecognized game result: {0}".format(game_text), file=self.stdout)
                         continue
-                    p = html.fragment_fromstring("<p>"+game_text+"</p>")
+                    p = html.fragment_fromstring("<p>" + game_text + "</p>")
                     replay_a = list(p.cssselect("a"))
                     if replay_a:
                         if not game.replay:
             self.tournament = Tournament.objects.get(slug=args[0])
         except Tournament.DoesNotExist:
             raise CommandError("Tournament {0} does not exist".format(args[0]))
-        self.site_url = args[1] if len(args)>1 else "http://afterhoursgaming.tv/sc2/"
+        self.site_url = args[1] if len(args) > 1 else "http://afterhoursgaming.tv/sc2/"
         admin_url = "http://ahgl.npinp.com/"
         if self.tournament.slug == "starcraft-2-season-1":
             self.first_week_match = datetime.date(2011, 6, 24)
-        
-        
+
         settings.INSTALLED_APPS.remove("notification")
-        
+
         try:
             if options['team']:
                 # Load teams
                     team_url = team_a.get('href')
                     team_name = " ".join(team_a.text_content().strip().split()[:-1])
                     self.load_team(team_url, team_name)
-                
+
             if options['match']:
                 # load groups
                 schedule_d = self.visit_url("schedule", self.site_url)
                 else:
                     round_lis = schedule_d.cssselect('#week-1-schedule li.season-list-item')
                 for i, group_li in enumerate(round_lis, start=1):
-                    round, created = TournamentRound.objects.get_or_create(order=i, stage_order=1, tournament=self.tournament, default={'stage_name':"Group"})
+                    round, created = TournamentRound.objects.get_or_create(order=i, stage_order=1, tournament=self.tournament, default={'stage_name': "Group"})
                     print("Round {0} retrieved, adding members".format(i), file=self.stdout)
                     for team_span in group_li.cssselect('.week-list-link > span.f2'):
                         team_slug = slugify(team_span.text.strip())
                             except Team.DoesNotExist:
                                 if not tried_nospace:
                                     print("Team {slug} not found...trying without spaces".format(slug=team_slug), file=self.stdout)
-                                    team_slug = team_slug.replace('-','')
+                                    team_slug = team_slug.replace('-', '')
                                     tried_nospace = True
                                 else:
                                     print("Team {slug} not found................skipping".format(slug=team_slug), file=self.stdout)
                                     break
-                        
+
                 # load matches
                 for week, week_li in enumerate(schedule_d.cssselect("li.season-list-item")):
                     for match_li in week_li.cssselect('li.week-list-item'):
                         match_url = list(match_li.cssselect('a.week-list-link'))[-1].get('href')
                         self.load_match(match_url, week)
-                
+
             # ----------- Admin site ------------------
             if options['admin']:
-                
+
                 # load lineups (extra match info)
                 lineup_d = self.visit_url("show-lineup", admin_url)
                 for a in lineup_d.cssselect("a"):
                     self.load_lineup(a.get('href'))
-                
+
                 # load results
                 result_d = self.visit_url("show-result", admin_url)
                 for a in result_d.cssselect("a"):
                     self.load_result(a.get('href'))
-                
+
             # ----------- Update stats ------------------
             for team in Team.objects.filter(tournament=self.tournament):
                 team.update_stats()
             for membership in TeamRoundMembership.objects.filter(tournamentround__tournament=self.tournament):
                 membership.update_stats()
-                            
+
         except Exception as e:
-            print('Error occured, dumping last document\n {0}'.format(tostring(self.d) if hasattr(self,"d") else None), file=self.stderr)
+            print('Error occurred, dumping last document\n {0}'.format(tostring(self.d) if hasattr(self, "d") else None), file=self.stderr)
             traceback.print_exc(file=self.stderr)
-            print(e, file=self.stderr)
+            print(e, file=self.stderr)

File ahgl/tournaments/models.py

View file
  • Ignore whitespace
 from collections import namedtuple
 import posixpath
 import logging
-import random, math
-from itertools import chain, count, takewhile, islice, groupby
+import math
+from itertools import count, takewhile, groupby
 import os.path
 
 from django.db import models
-from django.db.models import Q, Count, F
+from django.db.models import Count
 from django.utils.translation import ugettext_lazy as _
 from django.dispatch import receiver
 from django.db.models.signals import post_save
-from django.contrib.auth.models import User
-from django.contrib.sites.models import Site
 from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.template.defaultfilters import date, slugify
 
 logger = logging.getLogger(__name__)
 
+
 def validate_wholenumber(value):
     if value < 1:
         raise ValidationError(u'{0} is not a whole number'.format(value))
 
+
 class Tournament(models.Model):
     name = models.CharField(_("name"), max_length=50)
     slug = models.SlugField(max_length=50, primary_key=True)
     map_pool = models.ManyToManyField('Map')
     status = models.CharField(max_length=1, choices=(('C', 'Completed'), ('A', 'Active'), ('S', 'Signup'),), default='S', db_index=True)
     games_per_match = models.PositiveSmallIntegerField(default=5, verbose_name="Default Games per Match", validators=[validate_wholenumber])
-    structure = models.CharField(max_length=1, choices=(('I', 'Individual'),('T', 'Team'),), default='I')
-    
+    structure = models.CharField(max_length=1, choices=(('I', 'Individual'), ('T', 'Team'),), default='I')
+
     def random_teams(self, amount=7):
         return self.teams.order_by('?')[:amount]
-    
+
     def stages(self):
         return self.rounds.values('stage_name', 'stage_order').distinct().order_by('stage_order')
-    
+
     def __unicode__(self):
         return self.name
-    
+
     @models.permalink
     def get_absolute_url(self):
         return ('tournament', (), {'slug': self.slug,
                                    }
                 )
 
+
 class Map(models.Model):
     name = models.CharField(_("name"), max_length=50, primary_key=True)
     photo = ImageField(upload_to='map_photos', null=True, blank=True)
     # TODO:maybe add computed statistics later?