Fixed long lines

This commit is contained in:
2016-06-24 16:11:43 +02:00
parent 5c3c56ecc3
commit 589884c4be
5 changed files with 118 additions and 62 deletions

View File

@@ -22,23 +22,28 @@ from django import forms
from django.forms import ModelForm from django.forms import ModelForm
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.files.images import get_image_dimensions from django.core.files.images import get_image_dimensions
from tipp.models import Match, Competition, Post, UserProfile, Mandant, RelUserMandant from tipp.models import Match, Competition, Post, UserProfile, \
Mandant, RelUserMandant
class NumberInput(forms.TextInput): class NumberInput(forms.TextInput):
input_type = 'number' input_type = 'number'
class TippForm(forms.Form): class TippForm(forms.Form):
tippTeam1 = forms.IntegerField(required=True,widget=NumberInput(attrs={ tippTeam1 = forms.IntegerField(required=True,widget=NumberInput(
'cols': '2', attrs={
'min': '0', 'max': '99', 'step': '1', 'cols': '2',
'class':'form-inline', 'min': '0', 'max': '99', 'step': '1',
'role': 'form'} 'class':'form-inline',
'role': 'form'
}
)) ))
tippTeam2 = forms.IntegerField(required=True,widget=NumberInput(attrs={ tippTeam2 = forms.IntegerField(required=True,widget=NumberInput(
'cols': '2', attrs={
'min': '0', 'max': '99', 'step': '1', 'cols': '2',
'class':'form-inline', 'min': '0', 'max': '99', 'step': '1',
'role': 'form'} 'class':'form-inline',
'role': 'form'
}
)) ))
tippTeam1.widget.attrs['style'] = "width:35px" tippTeam1.widget.attrs['style'] = "width:35px"
tippTeam2.widget.attrs['style'] = "width:35px" tippTeam2.widget.attrs['style'] = "width:35px"

View File

@@ -67,11 +67,6 @@ class Match(models.Model):
leagueShortcut = models.CharField(max_length=12) leagueShortcut = models.CharField(max_length=12)
def __unicode__(self): def __unicode__(self):
"""
return (str(self.matchID) +
str(Team.objects.get(teamID=int(self.idTeam1)).values(name)) + " - " +
str(Team.objects.get(teamID=int(self.idTeam2)).values(name)))
"""
return (str(self.matchID)) return (str(self.matchID))
class Tipp(models.Model): class Tipp(models.Model):
@@ -79,7 +74,9 @@ class Tipp(models.Model):
tipperID = models.ForeignKey(User) tipperID = models.ForeignKey(User)
pointsTeam1 = models.PositiveSmallIntegerField() pointsTeam1 = models.PositiveSmallIntegerField()
pointsTeam2 = models.PositiveSmallIntegerField() pointsTeam2 = models.PositiveSmallIntegerField()
score = models.PositiveIntegerField(blank=True, null=True) score = models.PositiveIntegerField(
blank=True, null=True
)
class Meta: class Meta:
unique_together = ("matchID", "tipperID") unique_together = ("matchID", "tipperID")

View File

@@ -37,7 +37,9 @@ class OpenLiga(object):
# get a SUDS client object # get a SUDS client object
if self.proxyurl is None: if self.proxyurl is None:
try: try:
self.client = suds.client.Client('http://www.openligadb.de/Webservices/Sportsdata.asmx?WSDL') self.client = suds.client.Client(
'http://www.openligadb.de/'
+ 'Webservices/Sportsdata.asmx?WSDL')
except (urllib2.URLError): except (urllib2.URLError):
self.error += "Connect to webservice failed." self.error += "Connect to webservice failed."
else: else:
@@ -46,29 +48,43 @@ class OpenLiga(object):
proxy = urllib2.ProxyHandler({'http':proxyurl}) proxy = urllib2.ProxyHandler({'http':proxyurl})
opener = urllib2.build_opener(proxy) opener = urllib2.build_opener(proxy)
t.urlopener = opener t.urlopener = opener
self.client = suds.client.Client('http://www.openligadb.de/Webservices/Sportsdata.asmx?WSDL', transport=t) self.client = suds.client.Client(
'http://www.openligadb.de/Webservices/'
+ 'Sportsdata.asmx?WSDL', transport=t)
except urllib2.URLError as e: except urllib2.URLError as e:
self.error += "Connect to webservice failed (via proxy " + proxyurl + "): " + str(e) + "\n" self.error += "Connect to webservice failed " \
+ "(via proxy " + proxyurl + "): " + str(e) + "\n"
def getSeason(self, season, league='bl1'): def getSeason(self, season, league='bl1'):
""" Get the whole season. """ Get the whole season.
Args: season and league shortcut (optional) Args: season and league shortcut (optional)
""" """
return(self.client.service.GetMatchdataByLeagueSaison(leagueShortcut=league,leagueSaison=season)) return(self.client.service.GetMatchdataByLeagueSaison(
leagueShortcut=league,leagueSaison=season)
)
def getMatchday(self, season, matchdaynumber, league='bl1'): def getMatchday(self, season, matchdaynumber, league='bl1'):
""" Get matchday. """ Get matchday.
Args: season, matchdaynumber and league shortcut (optional) Args: season, matchdaynumber and league shortcut (optional)
""" """
return(self.client.service.GetMatchdataByGroupLeagueSaison(groupOrderID=matchdaynumber,leagueShortcut=league,leagueSaison=season)) return(self.client.service.GetMatchdataByGroupLeagueSaison(
groupOrderID=matchdaynumber,
leagueShortcut=league,
leagueSaison=season)
)
def getTeams(self, season, league='bl1'): def getTeams(self, season, league='bl1'):
return(self.client.service.GetTeamsByLeagueSaison(leagueShortcut=league,leagueSaison=season)) return(self.client.service.GetTeamsByLeagueSaison(
leagueShortcut=league,
leagueSaison=season)
)
def getCurrentGroup(self, league): def getCurrentGroup(self, league):
return(self.client.service.GetCurrentGroup(leagueShortcut=league)) return(self.client.service.GetCurrentGroup(
leagueShortcut=league)
)

View File

@@ -1,6 +1,6 @@
""" """
This file demonstrates writing tests using the unittest module. These will pass This file demonstrates writing tests using the unittest module.
when you run "manage.py test". These will pass when you run "manage.py test".
Replace this with more appropriate tests for your application. Replace this with more appropriate tests for your application.
""" """

View File

@@ -19,15 +19,18 @@ along with TipPy. If not, see <http://www.gnu.org/licenses/>.
""" """
from django.http import HttpResponse from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect, render, get_object_or_404 from django.shortcuts import render_to_response, redirect, render, \
get_object_or_404
from django.contrib.auth import authenticate, login from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import password_reset, password_reset_confirm from django.contrib.auth.views import password_reset, \
password_reset_confirm
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger from django.core.paginator import Paginator, InvalidPage, EmptyPage, \
PageNotAnInteger
from django.utils import timezone from django.utils import timezone
from django.utils.text import slugify from django.utils.text import slugify
from django.db.models import Sum, Max from django.db.models import Sum, Max
@@ -75,7 +78,9 @@ def profile(request, pk):
# If it's a HTTP POST, we're interested in processing form data. # If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST': if request.method == 'POST':
user_form = UserForm(data=request.POST, instance=user) user_form = UserForm(data=request.POST, instance=user)
profile_form = UserProfileForm(data=request.POST, instance=profile) profile_form = UserProfileForm(
data=request.POST, instance=profile
)
if user_form.is_valid() and profile_form.is_valid(): if user_form.is_valid() and profile_form.is_valid():
@@ -98,13 +103,18 @@ def profile(request, pk):
if 'avatar-clear' in request.POST: if 'avatar-clear' in request.POST:
if 'on' in request.POST['avatar-clear']: if 'on' in request.POST['avatar-clear']:
image = pjoin(settings.MEDIA_ROOT, img) image = pjoin(settings.MEDIA_ROOT, img)
debug.append('Is the image ' + str(image) + ' a regular file? ' + str(os.path.isfile(image))) debug.append('Is the image ' + str(image)
+ ' a regular file? '
+ str(os.path.isfile(image))
)
if os.path.isfile(image): if os.path.isfile(image):
os.remove(image) os.remove(image)
profile.save() profile.save()
for item in request.POST: for item in request.POST:
debug.append(str(item) + " -> " + str(request.POST[item])) debug.append(str(item) + " -> "
+ str(request.POST[item])
)
# Invalid form or forms - mistakes or something else? # Invalid form or forms - mistakes or something else?
# Print problems to the terminal. # Print problems to the terminal.
@@ -114,8 +124,8 @@ def profile(request, pk):
return redirect( '/accounts/profile/' + str(user.id) ) return redirect( '/accounts/profile/' + str(user.id) )
# Not a HTTP POST, so we render our form using two ModelForm instances. # Not a HTTP POST, so we render our form using two ModelForm
# These forms will be blank, ready for user input. # instances. These forms will be blank, ready for user input.
else: else:
user_form = UserForm( user_form = UserForm(
initial={ 'last_name': user.last_name, initial={ 'last_name': user.last_name,
@@ -151,7 +161,8 @@ def getSeason(request, ls, season):
for match in season[0]: for match in season[0]:
m = Match(matchID=unicode(match['matchID']), m = Match(matchID=unicode(match['matchID']),
matchDateTime=datetime.strptime(unicode(match['matchDateTime']), '%Y-%m-%d %H:%M:%S'), matchDateTime=datetime.strptime(
unicode(match['matchDateTime']), '%Y-%m-%d %H:%M:%S'),
group=int(match['groupID']), group=int(match['groupID']),
matchday=int(match['groupOrderID']), matchday=int(match['groupOrderID']),
matchday_name=unicode(match['groupName']), matchday_name=unicode(match['groupName']),
@@ -225,7 +236,8 @@ def update(request, ls, season, cur_md):
goals_total = match.pointsTeam1 + match.pointsTeam2 goals_total = match.pointsTeam1 + match.pointsTeam2
# Tipp is acurate # Tipp is acurate
if (tipp.pointsTeam1 == match.pointsTeam1 and tipp.pointsTeam2 == match.pointsTeam2): if (tipp.pointsTeam1 == match.pointsTeam1
and tipp.pointsTeam2 == match.pointsTeam2):
if goals_total >= 5: if goals_total >= 5:
score = scores.exact_high score = scores.exact_high
else: else:
@@ -289,7 +301,8 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
user = User.objects.get(username=request.user.username) user = User.objects.get(username=request.user.username)
""" get mandants current user is related """ """ get mandants current user is related """
mandants = RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True) mandants = RelUserMandant.objects.filter(user=request.user). \
values_list('mandant', flat=True)
""" get mates """ """ get mates """
tipp_mates = [] tipp_mates = []
@@ -320,7 +333,8 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
check if Tipp already exists check if Tipp already exists
""" """
try: try:
tipp = Tipp.objects.get(tipperID=user.id,matchID=match.matchID) tipp = Tipp.objects.get(tipperID=user.id,
matchID=match.matchID)
except ObjectDoesNotExist: except ObjectDoesNotExist:
tipp = None tipp = None
@@ -352,13 +366,15 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
if tipp is not None: if tipp is not None:
f = TippForm(prefix=str(match.matchID), f = TippForm(prefix=str(match.matchID),
initial={'tippTeam1': tipp.pointsTeam1, 'tippTeam2': tipp.pointsTeam2} initial={'tippTeam1': tipp.pointsTeam1,
'tippTeam2': tipp.pointsTeam2}
) )
else: else:
f = TippForm(prefix=str(match.matchID)) f = TippForm(prefix=str(match.matchID))
item = {} item = {}
item['matchDateTime'] = (match.matchDateTime.astimezone(timezoneLocal).strftime('%a %d.%m, %H:%M')) item['matchDateTime'] = (match.matchDateTime. \
astimezone(timezoneLocal).strftime('%a %d.%m, %H:%M'))
item['iconTeam1']= str(match.idTeam1.icon) item['iconTeam1']= str(match.idTeam1.icon)
item['iconURLTeam1'] = str(match.idTeam1.iconURL) item['iconURLTeam1'] = str(match.idTeam1.iconURL)
@@ -375,7 +391,8 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
if (match.pointsTeam1 == -1 or match.pointsTeam2 == -1): if (match.pointsTeam1 == -1 or match.pointsTeam2 == -1):
item['matchResult'] = "-:-" item['matchResult'] = "-:-"
else: else:
item['matchResult'] = str(match.pointsTeam1) + ":" + str(match.pointsTeam2) item['matchResult'] = str(match.pointsTeam1) + ":" \
+ str(match.pointsTeam2)
item['tippFormTeam1'] = f['tippTeam1'] item['tippFormTeam1'] = f['tippTeam1']
item['tippFormTeam2'] = f['tippTeam2'] item['tippFormTeam2'] = f['tippTeam2']
@@ -386,15 +403,17 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
for mate in tipp_mates: for mate in tipp_mates:
try: try:
matetipp = Tipp.objects.get(tipperID=mate['mate'],matchID=match.matchID) matetipp = Tipp.objects.get(tipperID=mate['mate'],
matchID=match.matchID)
if match_started is True: if match_started is True:
if matetipp.score is None: if matetipp.score is None:
score = u'\u231B' score = u'\u231B'
else: else:
score = matetipp.score score = matetipp.score
mate['tipps'].append(str(matetipp.pointsTeam1) + ":" + str(matetipp.pointsTeam2) + \ mate['tipps'].append(str(matetipp.pointsTeam1)
"(" + str(score) + ")") + ":" + str(matetipp.pointsTeam2)
+ "(" + str(score) + ")")
if match.finished is True: if match.finished is True:
mate['sum_score'] += matetipp.score mate['sum_score'] += matetipp.score
else: else:
@@ -405,11 +424,13 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
matches.append(item) matches.append(item)
# get the newest blogposts # get the newest blogposts
pm = RelPostMandant.objects.filter(mandant__in=mandants).values_list('post', flat=True) pm = RelPostMandant.objects.filter(mandant__in=mandants). \
values_list('post', flat=True)
posts = [] posts = []
for post in Post.objects.filter(id__in=pm, published=True)[:1]: for post in Post.objects.filter(id__in=pm, published=True)[:1]:
try: try:
avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name avatar = UserProfile.objects.get(user_id=post.author_id). \
avatar.name
except: except:
avatar = None avatar = None
posts.append( (post, avatar) ) posts.append( (post, avatar) )
@@ -428,31 +449,39 @@ def matchday(request, ls, season, matchday, template_name='md.html'):
'ls': ls, 'ls': ls,
'season': season, 'season': season,
'username': user, 'username': user,
'tipp_mates': sorted(tipp_mates, key=lambda k: k['sum_score'], reverse=True), 'tipp_mates': sorted(tipp_mates, key=lambda k: k['sum_score'],
reverse=True),
'posts': posts, 'posts': posts,
'has_refresh': has_refresh 'has_refresh': has_refresh
}) })
@login_required @login_required
def charts(request, ls, season, pos='default', template_name='charts.html'): def charts(request, ls, season, pos='default',
template_name='charts.html'):
debug = '' debug = ''
if pos == 'default': if pos == 'default':
if get_current_md(ls) < 18: if get_current_md(ls) < 18:
pos = 'hin' pos = 'hin'
matches = Match.objects.filter(leagueShortcut=ls, season=season, matchday__lte=17) matches = Match.objects.filter(leagueShortcut=ls,
season=season, matchday__lte=17)
else: else:
pos = 'rueck' pos = 'rueck'
matches = Match.objects.filter(leagueShortcut=ls, season=season, matchday__gte=18) matches = Match.objects.filter(leagueShortcut=ls,
season=season, matchday__gte=18)
elif pos == 'hin': elif pos == 'hin':
matches = Match.objects.filter(leagueShortcut=ls, season=season, matchday__lte=17) matches = Match.objects.filter(leagueShortcut=ls,
season=season, matchday__lte=17)
elif pos == 'rueck': elif pos == 'rueck':
matches = Match.objects.filter(leagueShortcut=ls, season=season, matchday__gte=18) matches = Match.objects.filter(leagueShortcut=ls,
season=season, matchday__gte=18)
else: else:
matches = Match.objects.filter(leagueShortcut=ls, season=season) matches = Match.objects.filter(leagueShortcut=ls, season=season)
# get mandants of current user # get mandants of current user
mandants = RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True) mandants = RelUserMandant.objects.filter(user=request.user). \
values_list('mandant', flat=True)
# main loop # main loop
mandant_dict = {} mandant_dict = {}
@@ -460,20 +489,23 @@ def charts(request, ls, season, pos='default', template_name='charts.html'):
mandant = Mandant.objects.get(id=m) mandant = Mandant.objects.get(id=m)
# get users # get users
users = RelUserMandant.objects.filter(mandant=m).values_list('user', flat=True) users = RelUserMandant.objects.filter(mandant=m). \
values_list('user', flat=True)
user_dict = {} user_dict = {}
for userid in users: for userid in users:
# get user object, then fetch matches for user # get user object, then fetch matches for user
user = User.objects.get(id=userid) user = User.objects.get(id=userid)
score = Tipp.objects.filter(matchID__in=matches, tipperID=user).aggregate(Sum('score')) score = Tipp.objects.filter(matchID__in=matches, \
tipperID=user).aggregate(Sum('score'))
if score['score__sum'] is None: if score['score__sum'] is None:
user_dict[user.first_name] = 0 user_dict[user.first_name] = 0
else: else:
user_dict[user.first_name] = score['score__sum'] user_dict[user.first_name] = score['score__sum']
mandant_dict[mandant.name] = sorted(user_dict.items(), key=lambda x: x[1], reverse=True) mandant_dict[mandant.name] = sorted(user_dict.items(),
key=lambda x: x[1], reverse=True)
return render(request, template_name, { return render(request, template_name, {
#'debug': debug, #'debug': debug,
@@ -487,13 +519,16 @@ def charts(request, ls, season, pos='default', template_name='charts.html'):
def blogindex(request, page): def blogindex(request, page):
# get the blog posts that are published # get the blog posts that are published
# and related to mandant # and related to mandant
mandants = RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True) mandants = RelUserMandant.objects.filter(user=request.user). \
posts = RelPostMandant.objects.filter(mandant__in=mandants).values_list('post', flat=True) values_list('mandant', flat=True)
posts = RelPostMandant.objects.filter(mandant__in=mandants). \
values_list('post', flat=True)
post_list = [] post_list = []
for post in Post.objects.filter(published=True, id__in=posts): for post in Post.objects.filter(published=True, id__in=posts):
try: try:
avatar = UserProfile.objects.get(user_id=post.author_id).avatar.name avatar = UserProfile.objects.get(user_id=post.author_id). \
avatar.name
except: except:
avatar = None avatar = None
post_list.append( (post, avatar) ) post_list.append( (post, avatar) )
@@ -519,7 +554,8 @@ def newBlogpost(request):
debug = '' debug = ''
has_mandant = False has_mandant = False
mandants = RelUserMandant.objects.filter(user=request.user).values_list('mandant', flat=True) mandants = RelUserMandant.objects.filter(user=request.user). \
values_list('mandant', flat=True)
choices = [] choices = []
if mandants.count > 1: if mandants.count > 1:
has_mandant = True has_mandant = True
@@ -541,10 +577,12 @@ def newBlogpost(request):
data = form_mandant.cleaned_data data = form_mandant.cleaned_data
for m in data['mandants']: for m in data['mandants']:
debug += str(m) + " " debug += str(m) + " "
m = RelPostMandant(post=p, mandant=Mandant.objects.get(name=m)) m = RelPostMandant(post=p,
mandant=Mandant.objects.get(name=m))
m.save() m.save()
else: else:
m = RelPostMandant(post=p, mandant=Mandant.objects.get(id=mandants[0])) m = RelPostMandant(post=p,
mandant=Mandant.objects.get(id=mandants[0]))
m.save() m.save()
return redirect( '/blog/1') return redirect( '/blog/1')