Example #1
0
    def get_context_data(self, **kwargs):
        title = getattr(settings, 'DEMO_PAGE_TITLE', 'Demo')
        intro_html = (getattr(settings, 'DEMO_PAGE_INTRO_HTML', '')
                      or getattr(settings, 'DEMO_PAGE_INTRO_TEXT', ''))
        context = super(DemoIndex, self).get_context_data(**kwargs)

        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append({
                'name':
                session_config['name'],
                'display_name':
                session_config['display_name'],
                'url':
                reverse('CreateDemoSession', args=(session_config['name'], )),
                'num_demo_participants':
                session_config['num_demo_participants']
            })

        context.update({
            'session_info': session_info,
            'title': title,
            'intro_html': intro_html,
            'is_debug': settings.DEBUG,
        })
        return context
Example #2
0
    def get_context_data(self, **kwargs):
        intro_text = settings.DEMO_PAGE_INTRO_TEXT
        context = super(DemoIndex, self).get_context_data(**kwargs)

        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append(
                {
                    'name': session_config['name'],
                    'display_name': session_config['display_name'],
                    'url': reverse(
                        'create_demo_session', args=(session_config['name'],)
                    ),
                    'num_demo_participants': session_config[
                        'num_demo_participants'
                    ]
                }
            )

        context.update({
            'session_info': session_info,
            'intro_text': intro_text,
            'is_debug': settings.DEBUG
        })
        return context
Example #3
0
    def get_context_data(self, **kwargs):
        title = getattr(settings, 'DEMO_PAGE_TITLE', 'Demo')
        intro_html = getattr(settings, 'DEMO_PAGE_INTRO_HTML', '') or getattr(
            settings, 'DEMO_PAGE_INTRO_TEXT', '')

        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append({
                'name':
                session_config['name'],
                'display_name':
                session_config['display_name'],
                'url':
                reverse('CreateDemoSession', args=(session_config['name'], )),
                'num_demo_participants':
                session_config['num_demo_participants'],
            })

        if os.environ.get('OTREEHUB_PUB'):
            otreehub_app_name = os.environ.get('OTREEHUB_APP_NAME')
            otreehub_url = f'https://www.otreehub.com/projects/{otreehub_app_name}/'
        else:
            otreehub_url = ''

        return super().get_context_data(
            session_info=session_info,
            title=title,
            intro_html=intro_html,
            is_debug=settings.DEBUG,
            otreehub_url=otreehub_url,
            **kwargs,
        )
Example #4
0
    def get_context_data(self, **kwargs):
        intro_text = settings.DEMO_PAGE_INTRO_TEXT
        context = super(DemoIndex, self).get_context_data(**kwargs)

        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append(
                {
                    'name': session_config['name'],
                    'display_name': session_config['display_name'],
                    'url': reverse(
                        'CreateDemoSession', args=(session_config['name'],)
                    ),
                    'num_demo_participants': session_config[
                        'num_demo_participants'
                    ]
                }
            )

        context.update({
            'session_info': session_info,
            'intro_text': intro_text,
            'is_debug': settings.DEBUG,
        })
        return context
Example #5
0
    def get_context_data(self, **kwargs):
        x = super().get_context_data(
            configs=SESSION_CONFIGS_DICT.values(),
            **kwargs,
        )

        return x
Example #6
0
    def get_context_data(self, **kwargs):
        title = getattr(settings, 'DEMO_PAGE_TITLE', 'Demo')
        intro_html = (
            getattr(settings, 'DEMO_PAGE_INTRO_HTML', '') or
            getattr(settings, 'DEMO_PAGE_INTRO_TEXT', ''))
        context = super(DemoIndex, self).get_context_data(**kwargs)

        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append(
                {
                    'name': session_config['name'],
                    'display_name': session_config['display_name'],
                    'url': reverse(
                        'CreateDemoSession', args=(session_config['name'],)
                    ),
                    'num_demo_participants': session_config[
                        'num_demo_participants'
                    ]
                }
            )

        context.update({
            'session_info': session_info,
            'title': title,
            'intro_html': intro_html,
            'is_debug': settings.DEBUG,
        })
        return context
Example #7
0
 def get_context_data(self, **kwargs):
     session_config_summaries = [
         info_about_session_config(session_config)
         for session_config in SESSION_CONFIGS_DICT.values()
     ]
     kwargs.update({'session_config_summaries': session_config_summaries})
     return super(CreateSession, self).get_context_data(**kwargs)
Example #8
0
    def vars_for_template(self):
        title = getattr(settings, 'DEMO_PAGE_TITLE', 'Demo')
        intro_html = getattr(settings, 'DEMO_PAGE_INTRO_HTML', '')
        session_info = []
        for session_config in SESSION_CONFIGS_DICT.values():
            session_info.append({
                'name':
                session_config['name'],
                'display_name':
                session_config['display_name'],
                'url':
                self.request.url_for('CreateDemoSession',
                                     config_name=session_config['name']),
                'num_demo_participants':
                session_config['num_demo_participants'],
            })

        if os.environ.get('OTREEHUB_PUB'):
            otreehub_app_name = os.environ.get('OTREEHUB_APP_NAME')
            otreehub_url = f'https://www.otreehub.com/projects/{otreehub_app_name}/'
        else:
            otreehub_url = ''

        return dict(
            session_info=session_info,
            title=title,
            intro_html=intro_html,
            is_debug=settings.DEBUG,
            otreehub_url=otreehub_url,
        )
Example #9
0
class CreateSessionForm(wtforms.Form):
    session_configs = SESSION_CONFIGS_DICT.values()
    session_config_choices = [(s['name'], s['display_name'])
                              for s in session_configs]

    session_config = wtforms.SelectField(
        choices=session_config_choices,
        validators=validators_required,
        render_kw=dict({'class': 'form-select'}),
    )

    num_participants = wtforms.IntegerField(
        validators=[
            wtvalidators.DataRequired(),
            wtvalidators.NumberRange(min=1)
        ],
        render_kw={
            'autofocus': True,
            'class': 'form-control w-auto'
        },
    )

    # too much weirdness with BooleanField and 'y'
    # so we render manually
    # it's a booleanfield so its default value will be 'y',
    # but it's a hidden widget that we are passing to the server
    # through .serializeArray, so we need to filter out
    is_mturk = wtforms.BooleanField()
    room_name = wtforms.StringField(widget=wtwidgets.HiddenInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.is_mturk.object_data:
            label = "Number of MTurk workers (assignments)"
            description = (
                'Since workers can return an assignment or drop out, '
                'some "spare" participants will be created: '
                f'the oTree session will have {settings.MTURK_NUM_PARTICIPANTS_MULTIPLE} '
                'times more participant objects than the number you enter here.'
            )
        else:
            label = "Number of participants"
            description = ''

        self.num_participants.label = label
        self.num_participants.description = description

    def validate(self):
        if not super().validate():
            return False

        config = SESSION_CONFIGS_DICT[self.session_config.data]
        lcm = config.get_lcm()
        if self.num_participants.data % lcm:
            self.num_participants.errors.append(
                'Please enter a valid number of participants.')
        return not bool(self.errors)
Example #10
0
 def get_context_data(self, **kwargs):
     return super().get_context_data(
         configs=SESSION_CONFIGS_DICT.values(),
         participant_urls=self.room.get_participant_urls(self.request),
         room_wide_url=self.room.get_room_wide_url(self.request),
         room=self.room,
         form=CreateSessionForm(room_name=self.room_name),
         collapse_links=True,
         **kwargs)
Example #11
0
 def get_context_data(self, **kwargs):
     x = super().get_context_data(
         configs=SESSION_CONFIGS_DICT.values(),
         # splinter makes request.GET.get('mturk') == ['1\\']
         # no idea why
         # so just see if it's non-empty
         **kwargs,
     )
     return x
Example #12
0
 def get_context_data(self, **kwargs):
     x = super().get_context_data(
         configs=SESSION_CONFIGS_DICT.values(),
         # splinter makes request.GET.get('mturk') == ['1\\']
         # no idea why
         # so just see if it's non-empty
         form=CreateSessionForm(is_mturk=bool(self.request.GET.get('is_mturk'))),
         **kwargs,
     )
     return x
Example #13
0
class CreateSessionForm(forms.Form):
    session_configs = SESSION_CONFIGS_DICT.values()
    session_config_choices = (
        # use '' instead of None. '' seems to immediately invalidate the choice,
        # rather than None which seems to be coerced to 'None'.
        [('', '-----')] +
        [(s['name'], s['display_name']) for s in session_configs])

    session_config = forms.ChoiceField(
        choices=session_config_choices, required=True)

    num_participants = forms.IntegerField(required=False)
    is_mturk = forms.BooleanField(
        widget=widgets.HiddenInput,
        initial=False,
        required=False
    )
    room_name = forms.CharField(
        initial=None,
        widget=widgets.HiddenInput,
        required=False
    )

    def __init__(self, *args, is_mturk=False, room_name=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['room_name'].initial = room_name
        if is_mturk:
            self.fields['is_mturk'].initial = True
            self.fields['num_participants'].label = "Number of MTurk workers (assignments)"
            self.fields['num_participants'].help_text = (
                'Since workers can return an assignment or drop out, '
                'some "spare" participants will be created: '
                f'the oTree session will have {settings.MTURK_NUM_PARTICIPANTS_MULTIPLE}'
                '{} times more participant objects than the number you enter here.'
            )
        else:
            self.fields['num_participants'].label = "Number of participants"

    def clean(self):
        super().clean()
        if self.errors:
            return
        session_config_name = self.cleaned_data['session_config']

        config = SESSION_CONFIGS_DICT[session_config_name]
        lcm = config.get_lcm()
        num_participants = self.cleaned_data.get('num_participants')
        if num_participants is None or num_participants % lcm:
            raise forms.ValidationError(
                'Please enter a valid number of participants.'
            )
Example #14
0
class CreateSessionForm(forms.Form):
    session_configs = SESSION_CONFIGS_DICT.values()
    session_config_choices = (
        # use '' instead of None. '' seems to immediately invalidate the choice,
        # rather than None which seems to be coerced to 'None'.
        [('', '-----')] +
        [(s['name'], s['display_name']) for s in session_configs])

    session_config = forms.ChoiceField(
        choices=session_config_choices, required=True)

    num_participants = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        for_mturk = kwargs.pop('for_mturk')
        super().__init__(*args, **kwargs)
        if for_mturk:
            self.fields['num_participants'].label = "Number of MTurk workers"
            self.fields['num_participants'].help_text = (
                'Since workers can return the HIT or drop out, '
                'some "spare" participants will be created: '
                'the oTree session will have '
                '{} times more participants than the MTurk HIT. '
                'The number you enter in this field is number of '
                'workers required for your HIT.'.format(
                    settings.MTURK_NUM_PARTICIPANTS_MULTIPLE
                )
            )
        else:
            self.fields['num_participants'].label = "Number of participants"

    def clean_num_participants(self):
        session_config_name = self.cleaned_data.get('session_config')

        # I think when this is checked, it's possible that basic validation
        # for session_config_name was not done yet.
        # when I tested it was None
        # but maybe it could also be the empty string because that's what's
        # explicitly put above.
        if session_config_name:
            lcm = SESSION_CONFIGS_DICT[session_config_name].get_lcm()
            num_participants = self.cleaned_data['num_participants']
            if num_participants % lcm:
                raise forms.ValidationError(
                    'Please enter a valid number of participants.'
                )
            return num_participants
Example #15
0
 def render_to_response(self, context):
     session = Session.objects.get(code=self.kwargs['session_code'])
     events_by_app_name_then_group = defaultdict(lambda: {})
     for session_config in SESSION_CONFIGS_DICT.values():
         app_name = session_config['name']
         try:
             groups_query = getattr(session, app_name + '_group')
         except AttributeError:
             continue
         groups = list(groups_query.all())
         if groups:
             for group in groups:
                 events = Event.objects.filter(group_pk=group.pk)
                 events_by_app_name_then_group[app_name][group.pk] = [
                     e.message for e in events
                 ]
     return JsonResponse(events_by_app_name_then_group, safe=False)
Example #16
0
class CreateSessionForm(forms.Form):
    session_configs = SESSION_CONFIGS_DICT.values()
    session_config_choices = (
        [('', '-----')] +
        [(s['name'], s['display_name']) for s in session_configs])

    session_config = forms.ChoiceField(
        choices=session_config_choices, required=True)

    num_participants = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        for_mturk = kwargs.pop('for_mturk')
        super(CreateSessionForm, self).__init__(*args, **kwargs)
        if for_mturk:
            self.fields['num_participants'].label = "Number of workers"
            self.fields['num_participants'].help_text = (
                'Since workers can return the hit or drop out '
                '"spare" participants will be created. Namely server will '
                'have %s times more participants than MTurk HIT. '
                'The number you enter in this field is number of '
                'workers required for your HIT.'
                % settings.MTURK_NUM_PARTICIPANTS_MULTIPLE
            )
        else:
            self.fields['num_participants'].label = "Number of participants"

    def clean_num_participants(self):
        session_config_name = self.cleaned_data.get('session_config')

        # We must check for an empty string in case validation is not run
        if session_config_name != '':
            lcm = SESSION_CONFIGS_DICT[session_config_name].get_lcm()
            num_participants = self.cleaned_data['num_participants']
            if num_participants % lcm:
                raise forms.ValidationError(
                    'Please enter a valid number of participants.'
                )
            return num_participants
Example #17
0
 def get_context_data(self, **kwargs):
     session_config_summaries = [
         session_config.get_info()
         for session_config in SESSION_CONFIGS_DICT.values()]
     kwargs.update({'session_config_summaries': session_config_summaries})
     return super(CreateSession, self).get_context_data(**kwargs)
Example #18
0
    url_name = 'redwood_debug'
    url_pattern = r'^redwood/debug/session/(?P<session_code>[a-zA-Z0-9_-]+)/$'
    template_name = 'otree_redwood/Debug.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['stats'] = stats.items()
        channel_layer = channels.asgi.get_channel_layer()
        if 'statistics' in channel_layer.extensions:
            context['global_channel_stats'] = channel_layer.global_statistics()
        context['connected_participants'] = Connection.objects.all()
        context['session_code'] = self.kwargs['session_code']
        return context


app_specific_exports = []
for session_config in SESSION_CONFIGS_DICT.values():
    app_name = session_config['name']
    dotted_path = app_name + '.views'
    display_name = session_config['display_name']
    try:
        module = import_module(dotted_path)
    except ImportError:
        continue
    table_fn = getattr(module, 'get_output_table', None)
    header_fn = getattr(module, 'get_output_table_header', None)
    if table_fn and header_fn:
        app_specific_exports.append(
            AppSpecificExportCSV(app_name, display_name, table_fn, header_fn))
Example #19
0
 def get_context_data(self, **kwargs):
     kwargs['configs'] = SESSION_CONFIGS_DICT.values()
     return super().get_context_data(**kwargs)
Example #20
0
 def get_context_data(self, **kwargs):
     kwargs['configs'] = SESSION_CONFIGS_DICT.values()
     return super().get_context_data(**kwargs)