Beispiel #1
0
def add_score(request):
  if request.method != 'POST':
    players = Player.gql("WHERE owner = :owner AND active = True ORDER BY name", owner=request.user)
    return render_to_response(request, 'pingpong/addscore.html',
      { 'players': players, })
  else:
    mode = 'singles' # Used when we re-direct back to the main view
    try:
      # Find players. Save teams. Save game using a ranking system.
      t1p1 = get_object(Player, request.POST['t1p1'])
      t1p2 = get_object(Player, request.POST['t1p2'])
      t2p1 = get_object(Player, request.POST['t2p1'])
      t2p2 = get_object(Player, request.POST['t2p2'])
      t1s = float(request.POST['t1s'])
      t2s = float(request.POST['t2s'])
      t1 = db_create(Team, player1=t1p1, player2=t1p2, points=t1s)
      t2 = db_create(Team, player1=t2p1, player2=t2p2, points=t2s)
      game = db_create(Game, team1=t1, team2=t2)
      save_player_games(game, t1p1, t1p2, t2p1, t2p2, t1s, t2s)
      doubles = (t1p1 != None and t1p2 != None and t2p1 != None and t2p2 != None)
      if doubles:
        mode = 'doubles'
      ranking_system = DefaultRankingSystem()
      ranking_system.save_game(t1p1=t1p1, t1p2=t1p2, t2p1=t2p1, t2p2=t2p2, 
        t1s=t1s, t2s=t2s, t1=t1, t2=t2, game=game, doubles=doubles)
      response_dict = { 'status': True, 'message': 'Scores successfully saved.', 
        'mode': mode, 'game': str(game.key()) }
    except:
      logging.exception('There was a problem adding scores')
      response_dict = { 'status': False, 'message' : 'Hmmm... There was a problem saving your scores - please have another go.', 'mode': mode }
    return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
    def process_request(self, request):
        # Ignore port if it's 80 or 443
        if ':' in request.get_host():
            domain, port = request.get_host().split(':')
            if int(port) not in (80, 443):
                domain = request.get_host()
        else:
            domain = request.get_host().split(':')[0]

        # Try exact domain and fall back to with/without 'www.'
        site = Site.all().filter('domain =', domain).get()
        if not site:
            if domain.startswith('www.'):
                fallback_domain = domain[4:]
            else:
                fallback_domain = 'www.' + domain
            site = Site.all().filter('domain =', fallback_domain).get()

        # Add site if it doesn't exist
        if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY', True):
            site = db_create(Site, domain=domain, name=domain)
            site.put()

        # Set SITE_ID for this thread/request
        if site:
            SITE_ID.value = str(site.key())
        else:
            SITE_ID.value = _default_site_id
Beispiel #3
0
def settings(request):
  if request.method != 'POST':
    players = Player.gql("WHERE owner = :owner AND active = True ORDER BY name", owner=request.user)
    return render_to_response(request, 'pingpong/settings.html',
      { 'players': players, 'email': request.user.email })
  else:
    errors = {}
    try:
      # Save email address
      email = request.POST['email']
      if is_valid_email(email.strip()):
        user = request.user
        user.email = email.strip()
        user.save()
      else:
        errors['email'] = 'Invalid email address'

      # Add any new players
      new_players = request.POST['newplayers']
      if new_players:
        players = new_players.splitlines()
        for p in players:
          if len(p.strip()) > 0:
            db_create(Player, name=p.strip(), owner=request.user)

      # Update player names based on posted values
      for k, v in request.POST.items():
        if str(k).endswith('_player'): # Expected key format: <key>_player
          player = get_object(Player, str(k)[:-7])
          if player:
            if len(v.strip()) > 0:
              player.name = v # Value is the updated player name
              player.put()
            else:
              errors[str(k)[:-7]] = 'Invalid name'

      if len(errors) == 0:
        response_dict = { 'status': True, 'message': 'Settings successfully saved.' }
      else:
        response_dict = { 'status': False, 'message': 'Hmmm... There was a problem saving your settings - please have another go.',
          'errors': errors }
      return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
    except:
      logging.exception('There was a problem saving settings')
      response_dict = { 'status': False, 'message': 'Hmmm... There was a problem saving your settings - please have another go.',
        'errors': errors }
    return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
Beispiel #4
0
def save_player_games(game, p1, p2, p3, p4, t1s, t2s):
  if p1 != None:
    db_create(PlayerGame, player=p1, game=game, date_played=game.date_played, won=game.won(p1),
              t1p1=p1, t1p2=p2, t2p1=p3, t2p2=p4, team1_points=t1s, team2_points=t2s)
  if p2 != None:
    db_create(PlayerGame, player=p2, game=game, date_played=game.date_played, won=game.won(p2),
              t1p1=p1, t1p2=p2, t2p1=p3, t2p2=p4, team1_points=t1s, team2_points=t2s)
  if p3 != None:
    db_create(PlayerGame, player=p3, game=game, date_played=game.date_played, won=game.won(p3),
              t1p1=p1, t1p2=p2, t2p1=p3, t2p2=p4, team1_points=t1s, team2_points=t2s)
  if p4 != None:
    db_create(PlayerGame, player=p4, game=game, date_played=game.date_played, won=game.won(p4),
              t1p1=p1, t1p2=p2, t2p1=p3, t2p2=p4, team1_points=t1s, team2_points=t2s)
Beispiel #5
0
    def create_user(self, rpx_auth_info):
        """Creates user based on the RPX authentication info."""
        username = rpx_auth_info.get_user_name()

        user = dbutils.db_create(User, username=username, email=rpx_auth_info.get_email())
        if not user:
            raise Exception('Cannot create user (name = %s)' % username)
        self.logger.debug("RpxBackend: Created user(%s) as %s\r\n" % (user.username, str(user)))
        user.is_active = True
        user.is_staff = False
        user.is_superuser = False
        user.set_unusable_password()
        user.save()
        rpxdata = RpxData(key_name=self.create_rpx_key(rpx_auth_info.get_rpx_id()), user=user)
        rpxdata.save()
        self.logger.debug("RpxBackend: RpxData created\r\n")

        return user
Beispiel #6
0
def create_profile(request, form_class=None, success_url=None,
                   template_name='profiles/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.
    
    If the user already has a profile, as determined by
    ``request.user.get_profile()``, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view. If no profile model has
    been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    **Optional arguments:**
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.
        
        If this argument is not supplied, this view will use a
        ``ModelForm`` automatically generated from the model specified
        by ``AUTH_PROFILE_MODULE``.
    
    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.
    
    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.
    
    **Context:**
    
    ``form``
        The profile-creation form.
    
    **Template:**
    
    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.
    
    """
    try:
        profile_obj = request.user.get_profile()
        if profile_obj:
            return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass
    
    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #
    
    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={ 'username': request.user.username })
    if form_class is None:
        form_class = utils.get_profile_form()
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            
            profile_obj = db_create(Prayerprofile,
                fname       = form.cleaned_data['fname'],
                nickname    = form.cleaned_data['nickname'],
                gender      = form.cleaned_data['gender'],
                bday        = form.cleaned_data['bday'],
                location    = form.cleaned_data['location'],
                avatar      = form.cleaned_data['avatar'],
                date_updated= form.cleaned_data['date_updated'],
                date_joined = form.cleaned_data['date_joined'],
                privacy     = form.cleaned_data['privacy'],
                latest_news = form.cleaned_data['latest_news'],
                user = request.user
            )
            profile_obj.save()
            
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)
Beispiel #7
0
    p.singles_last_movement = 0.0
    p.singles_ranking_points = 100.0
    p.put()

# Creating new PlayerGame entities for extant data
from ragendja.dbutils import db_create
from pingpong.models import Player, Team, Game, PlayerGame

for p in Player.all():
  # Find all teams where p is player1 (no gql OR operator)
  teams = Team.gql("WHERE player1 = :player", player=p)
  for t in teams:
    # Delete all games in which t played
    games = Game.gql("WHERE team1 = :team", team=t)
    for g in games:
      db_create(PlayerGame, player=p, game=g, date_played=g.date_played)
    games = Game.gql("WHERE team2 = :team", team=t)
    for g in games:
      db_create(PlayerGame, player=p, game=g, date_played=g.date_played)
  # Find all teams where p is player2 (no gql OR operator)
  teams = Team.gql("WHERE player2 = :player", player=p)
  for t in teams:
    # Delete all games in which t played
    games = Game.gql("WHERE team1 = :team", team=t)
    for g in games:
      db_create(PlayerGame, player=p, game=g, date_played=g.date_played)
    games = Game.gql("WHERE team2 = :team", team=t)
    for g in games:
      db_create(PlayerGame, player=p, game=g, date_played=g.date_played)

# Populating extant PlayerGame entities with new won property