def ajax_search(request, search_form, request_uri=None):

    request_uri_for_form = {
        FilterPlayersByVariantsForm:
        reverse('accounts:ajax-filter-players-by-variant'),
        SearchPlayersByKeywordsForm:
        reverse('accounts:ajax-search-players-by-kw'),
    }

    def search(obj_response, form_data):
        form = search_form(request, data=form_data)
        if form.is_valid():
            profiles_for_game = form.search()
            context = {
                'profiles_for_game':
                profiles_for_game,
                'MEDIA_URL':
                settings.MEDIA_URL,
                'STATIC_URL':
                settings.STATIC_URL,
                'request':
                request,
                'paginate_players_per_page':
                settings.ENDLESS_PAGINATE_PLAYERS_PER_PAGE,
            }
            players_count_str = "<h3>%s total players</h3>" % profiles_for_game.count(
            )
            obj_response.html("#id_players-count", players_count_str)
            players_tmpl = """
            {% load endless %}
            {% paginate paginate_players_per_page profiles_for_game as players %}
                {% include "accounts/_players_table.html" %}
            """
            t = Template(players_tmpl)
            players_table = t.render(Context(context))
            obj_response.html('#id_players-table', players_table)

            pag_tmpl = """
            {% load endless %}
            {% paginate paginate_players_per_page profiles_for_game %}
                {% include "accounts/_pagination.html" %}
            """
            t = Template(pag_tmpl)
            pagination = t.render(Context(context))
            obj_response.html('div#profile-pagination', pagination)
        else:
            log.debug('find players filter errors: %s', form.errors)

    instance = Sijax()
    instance.set_data(request.POST)
    instance.set_request_uri(request_uri_for_form.get(search_form, ''))
    instance.register_callback('search', search)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
예제 #2
0
    def test_changing_uris_results_in_a_differnt_js_output(self):
        inst = Sijax()

        req_uri = "http://localhost:8080/submit_here"
        json_uri = "http://localhost:8080/json2.js"

        inst.set_request_uri(req_uri)
        js = inst.get_js()
        self.assertTrue('Sijax.setRequestUri("%s");' % req_uri in js)
        self.assertFalse('Sijax.setJsonUri' in js)

        inst.set_json_uri(json_uri)
        js = inst.get_js()
        self.assertTrue('Sijax.setRequestUri("%s");' % req_uri in js)
        self.assertTrue('Sijax.setJsonUri("%s");' % json_uri in js)
예제 #3
0
    def test_changing_uris_results_in_a_differnt_js_output(self):
        inst = Sijax()

        req_uri = "http://localhost:8080/submit_here"
        json_uri = "http://localhost:8080/json2.js"

        inst.set_request_uri(req_uri)
        js = inst.get_js()
        self.assertTrue('Sijax.setRequestUri("%s");' % req_uri in js)
        self.assertFalse('Sijax.setJsonUri' in js)

        inst.set_json_uri(json_uri)
        js = inst.get_js()
        self.assertTrue('Sijax.setRequestUri("%s");' % req_uri in js)
        self.assertTrue('Sijax.setJsonUri("%s");' % json_uri in js)
예제 #4
0
def ajax_load_languages_by_game(request, instance_id):
    def load_options(obj_response, instance_id):
        game = Instance.objects.get(pk=instance_id)
        langs = game.languages.values_list('pk',
                                           'name').distinct().order_by('code')
        out = ""
        for id, name in langs:
            out += '<option value="%s">%s</option>' % (id, name)
        obj_response.html('#id_0-preferred_language', out)

    instance = Sijax()
    instance.set_data(request.POST)
    uri = reverse('instances:ajax-load-languages-by-game',
                  args=(instance_id, ))
    instance.set_request_uri(uri)
    instance.register_callback('load_languages_by_game', load_options)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
    return HttpResponse("")
예제 #5
0
def ajax_load_games_by_city(request, for_city_id):
    def load_options(obj_response, for_city_id):
        #games_for_city = Instance.objects.filter(for_city__pk=for_city_id).language(get_language())
        games = Instance.objects.exclude(
            is_disabled=True).filter(for_city__pk=for_city_id).values_list(
                'pk', 'title').distinct().order_by('title')
        out = ""
        for id, title in games:
            out += '<option value="%s">%s</option>' % (id, title)
        obj_response.html('#id_0-instance', out)

    instance = Sijax()
    instance.set_data(request.POST)
    uri = reverse('instances:ajax-load-games-by-city', args=(for_city_id, ))
    instance.set_request_uri(uri)
    instance.register_callback('load_games_by_city', load_options)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
    return HttpResponse("")
def all(request, template='accounts/all.html'):
    profiles_for_game =  UserProfilePerInstance.objects.select_related().\
            filter(
                instance=request.current_game
        ).exclude(user_profile__user__is_active=False
        ).order_by('-date_created')
    filter_by_variants = Sijax()
    filter_by_variants.set_request_uri(
        reverse('accounts:ajax-filter-players-by-variant'))

    search_by_kw = Sijax()
    search_by_kw.set_request_uri(reverse('accounts:ajax-search-players-by-kw'))

    context = {
        'profiles_for_game': profiles_for_game,
        'filter_by_variants_form': FilterPlayersByVariantsForm(request),
        'search_by_kw_form': SearchPlayersByKeywordsForm(request),
        'filter_by_variants_sijax_js': filter_by_variants.get_js(),
        'search_by_kw_sijax_js': search_by_kw.get_js(),
        'paginate_players_per_page':
        settings.ENDLESS_PAGINATE_PLAYERS_PER_PAGE,
    }

    return render(request, template, context)
def profile(request, id, template_name="accounts/profile.html"):

    if hasattr(request, 'current_game'):
        instance = request.current_game
    else:
        raise Http404("could not locate a valid game")

    context = {}
    player = get_object_or_404(User, id=id)
    kwargs = {}
    kwargs['instance'] = request.current_game
    kwargs['user_profile'] = request.user.get_profile(
    ) if request.user == player else player.get_profile()
    try:
        my_game_profile = UserProfilePerInstance.objects.get(**kwargs)
    except UserProfilePerInstance.DoesNotExist:
        raise Http404("user for this game is not registered")

    if request.method == 'POST':
        this_page = reverse('accounts:player_profile', args=(id, ))

        form = CommentForm(data=request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            log.debug("processed comment_form. cleaned_data: %s" % cd)
            comment_parent = get_object_or_404(UserProfilePerInstance,
                                               id=cd.get('parent_id'))
            comment = comment_parent.comments.create(
                content_object=comment_parent,
                message=cd.get(u'message'),
                user=request.user,
                instance=request.current_game,
            )
            if request.POST.has_key(
                    'video-url') and request.POST.get('video-url') != '':
                create_video_attachment(comment, request.POST.get('video-url'),
                                        request.current_game, request.user)

            if request.FILES.has_key('picture'):
                create_image_attachment(comment, request.FILES.get('picture'),
                                        request.current_game, request.user)

            stream_verb = 'commented'
            stream_utils.action.send(
                request.user,
                stream_verb,
                target=comment_parent,
                action_object=comment,
                description="commented on a user profile",
            )
            if request.user != comment_parent.user_profile.user:
                message = '%s commented on your profile.' % request.user.get_profile(
                ).screen_name
                comment_parent.user_profile.user.notifications.create(
                    content_object=comment, message=message)

            redirect(
                reverse('accounts:player_profile',
                        args=(comment_parent.user_profile.user.pk, )))

    my_games = Instance.objects.exclude(is_disabled=True).filter(
        pk__in=UserProfilePerInstance.objects.filter(
            user_profile=player.get_profile()).values_list('instance__pk',
                                                           flat=True))
    stream = Action.objects.get_for_actor( player).\
            exclude(verb='user_logged_in').order_by('-datetime')[:10]

    create_comment_sijax = Sijax()
    create_comment_sijax.set_request_uri(reverse('comments:ajax-create'))
    context.update({
        'create_comment_sijax_js': create_comment_sijax.get_js(),
    })

    context.update({
        'player': player,
        'profile_per_instance': my_game_profile,
        'stream': stream,
        'affiliations': my_game_profile.affils.all(),
        'my_games': my_games,
    })
    # this line here updates the context with
    # mission, my_points_for_mission and progress_percentage
    return render(request, template_name, context)
def _build_context(request, action, activity, user=None):

    context = {}
    activity_type = activity.activity_type_readable

    def _get_related():
        if activity_type == 'open_ended':
            return getattr(activity, 'openended_answers')
        elif activity_type == 'empathy':
            return getattr(activity, 'empathy_answers')
        elif activity_type == 'multi_response':
            return getattr(activity, 'multichoice_answers')
        else:
            for klass in ['AnswerMap', 'AnswerSingleResponse']:
                related_name = klass.replace('Answer', '').lower() + '_answers'
                if hasattr(activity, related_name):
                    return getattr(activity, related_name)

    if action == 'overview':

        create_comment_sijax = Sijax()
        create_comment_sijax.set_request_uri(reverse('comments:ajax-create'))
        context.update({
            'create_comment_sijax_js':
            create_comment_sijax.get_js(),
        })

        if activity_type != 'multi_response':
            answers = activity.__class__.objects.none()
            myAnswer = None
            myComment = None
            related = _get_related()
            if related:
                answers = related.filter(activity=activity)
                if user:
                    try:
                        myAnswer = related.get(activity=activity,
                                               answerUser=user)
                        my_comments = myAnswer.comments.all().order_by(
                            'posted_date')
                        myComment = None
                        if my_comments.count():
                            myComment = my_comments[0]
                    except:
                        pass
            context.update(
                dict(
                    answers=answers,
                    myAnswer=myAnswer,
                    myComment=myComment,
                ))

        if activity_type in ['multi_response', 'single_response']:
            choices = MultiChoiceActivity.objects.by_activity(
                activity=activity)
            context.update({'choices': choices})

            if activity_type == "multi_response":
                answers = AnswerMultiChoice.objects.answers_by_activity(
                    activity)
                my_comment = None
                my_answers = None
                answer_dict = {}
                for answer in answers:
                    answer_user = answer.get_user()
                    if not answer_dict.has_key(answer_user):
                        answer_dict[answer_user] = {
                            'answers': [],
                            'comments': []
                        }
                    answer_dict[answer_user]['answers'].append(
                        '<li>%s</li>' % answer.option_value)
                    for comment in answer.comments.all():
                        if user:
                            if not my_comment:
                                my_comment = comment
                        answer_dict[answer_user]['comments'].append(comment)
                all_answers = []
                if user and user in answer_dict:
                    my_answers = mark_safe(
                        '<ul>' + ''.join(answer_dict[user]['answers']) +
                        '</ul>')
                for user, data in sorted(answer_dict.items()):
                    all_answers.append(
                        (user,
                         mark_safe('<ul>' + ''.join(data['answers']) +
                                   '</ul>'), data['comments']))
                #log.debug('overview multi my answers %s' % my_answers)
                #log.debug('overview multi all answers %s' % all_answers)
                #print all_answers
                context.update(
                    dict(all_answers=all_answers,
                         my_answers=my_answers,
                         my_comment=my_comment))
        elif activity_type == 'map':
            answers = AnswerMap.objects.filter(activity=activity)
            init_coords = []
            x = 0
            map = None
            for answer in answers:
                map = answer.map
                message = None
                if answer.comments.count():
                    message = answer.comments.all()[0].message or None
                player = answer.answerUser.get_profile().screen_name

                markers = simplejson.loads("%s" % map)["markers"]
                for coor in markers if markers != None else []:
                    coor = coor["coordinates"]
                    init_coords.append([x, coor[0], coor[1], message, player])
                    x = x + 1

            if not map:
                map = activity.mission.parent.location
            context.update(dict(
                init_coords=init_coords,
                map=map,
            ))

    elif action == 'play':
        if activity_type == 'open_ended':
            form = make_openended_form()
        elif activity_type == 'empathy':
            form = make_empathy_form()
        elif (activity_type == "single_response"):
            choices = _get_mc_choices(activity)
            form = make_single_form(choices)
        elif (activity_type == "multi_response"):
            choices = _get_mc_choices(activity)
            form = make_multi_form(choices)
        elif (activity_type == "map"):
            form = MapForm()
            init_coords = []
            x = 0
            answer = AnswerMap.objects.filter(activity=activity,
                                              answerUser=user)
            if answer.count():
                map = answer[0].map
                markers = simplejson.loads("%s" % map)["markers"]
                x = 0
                for coor in markers if markers != None else []:
                    coor = coor["coordinates"]
                    init_coords.append([x, coor[0], coor[1]])
                    x = x + 1
            else:
                map = activity.mission.parent.location
            context.update({'map': map})

        context.update({'form': form})

    if user:
        context['is_completed'] = activity.is_completed(user)
    return context