Exemple #1
0
def create_judge_pdf(request):
    squads = Squad.objects.all() \
        .prefetch_related('athlete_set') \
        .select_related('athlete_set__stream')

    squad_athletes_dict = { 
        squad.id: squad.athlete_set.order_by('squad_position').select_related('stream') for squad in squads
    }

    squad_difficulty_indices = { squad.id: {} for squad in squads }
    for squad in squads:
        previous_athlete = None
        athletes_in_stream = 0
        for athlete in squad_athletes_dict[squad.id]:
            if previous_athlete and athlete.stream != previous_athlete.stream:
                squad_difficulty_indices[squad.id][previous_athlete.id] = athletes_in_stream
                athletes_in_stream = 0
            athletes_in_stream += 1
            previous_athlete = athlete
        squad_difficulty_indices[squad.id][previous_athlete.id] = athletes_in_stream

    squad_disciplines_dict = { squad.id: squad.get_disciplines(squad.athlete_set.all()) for squad in squads }

    context = {
        'squads': squads,
        'squad_disciplines_dict': squad_disciplines_dict,
        'squad_athletes_dict': squad_athletes_dict,
        'squad_difficulty_indices': squad_difficulty_indices,
    }
    template_location = 'gymnastics/documents/squads_judges.tex'
    file_name = '{0}_{1}_{2}.pdf'.format(ugettext_lazy('Squads'), ugettext_lazy('Judge'), ugettext_lazy('Lists'))

    return pdf.create(template_location, context, file_name)
Exemple #2
0
 def clean(self):
     super(PagePermissionInlineAdminForm, self).clean()
     for field in self.Meta.model._meta.fields:
         if not isinstance(field, BooleanField) or not field.name.startswith('can_'):
             continue
         name = field.name
         self.cleaned_data[name] = self.cleaned_data.get(name, False)
     
     can_add = self.cleaned_data['can_add']
     can_edit = self.cleaned_data['can_change']
     # check if access for childrens, or descendants is granted
     if can_add and self.cleaned_data['grant_on'] == ACCESS_PAGE:
         # this is a missconfiguration - user can add/move page to current
         # page but after he does this, he will not have permissions to 
         # access this page anymore, so avoid this
         raise forms.ValidationError(ugettext_lazy('Add page permission requires also access to children, or descendants, otherwise added page can\'t be changed by its creator.'))
     
     if can_add and not can_edit:
         raise forms.ValidationError(ugettext_lazy('Add page permission also requires edit page permission.'))
     # TODO: finish this, but is it really required? might be nice to have 
     
     # check if permissions assigned in cms are correct, and display an message
     # if not - correctness mean: if user has add permisson to page, but he
     # does'nt have auth permissions to add page object, display warning
     return self.cleaned_data
 def __init__(self, attrs=None, unknown_label=None):
     super(NullBooleanRadioSelect, self).__init__(attrs=attrs)
     self.choices = (
         ('1', ugettext_lazy(unknown_label or 'Unknown')),
         ('2', ugettext_lazy('Yes')),
         ('3', ugettext_lazy('No'))
     )
Exemple #4
0
def File_form(request):
    if request.method == 'GET':
        form = FileForm()
        data_for_templete = {'form' : form}
        rc = RequestContext(request, {})
        rc.autoescape = False
        return render_to_response('stock_info/fileimport.html', data_for_templete, rc)
    else:
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            
            data = form.cleaned_data['file_name']
            try:
                results = Data_import(data)
                err_msg = []
                if results['not_found']:
                    err_msg.append(unicode(ugettext_lazy('Not found operations: %d' % results['not_found'])))
                if results['failed']:
                    err_msg.append(unicode(ugettext_lazy('Failed rows: %d' % results['failed'])))
                if len(err_msg) > 0:
                    messages.error(request, '; '.join(err_msg))
                else:
                    messages.info(request, unicode(ugettext_lazy('Success: %s rows' % results['success'])))
            except:
                messages.error(request, ugettext_lazy('Import failed'))
    return HttpResponseRedirect('/admin/stock_info/orderfailure')
Exemple #5
0
 def render_as_field(self, show_help_text=True, extra_context={}):
     context = {
         'choose_another_text_str': ugettext_lazy("Choose another page"),
         'choose_one_text_str': ugettext_lazy("Choose a page"),
     }
     context.update(extra_context)
     return super(BasePageChooserPanel, self).render_as_field(show_help_text, context)
Exemple #6
0
 def __init__(self):
     super(AvgTrafficSize, self).__init__(
         size_recv={'type': 'AREA', 'color': '#FF9900',
                    "legend": ugettext_lazy("received size")},
         size_sent={"type": "AREA", "color": "#339999",
                    "legend": ugettext_lazy("sent size")}
     )
    def testTestMode_Issue15(self):
        __current_test_mode_setting = settings.CAPTCHA_TEST_MODE
        settings.CAPTCHA_TEST_MODE = False
        r = self.client.get(reverse("captcha-test"))
        self.assertEqual(r.status_code, 200)
        r = self.client.post(
            reverse("captcha-test"),
            dict(captcha_0="abc", captcha_1="wrong response", subject="xxx", sender="*****@*****.**"),
        )
        self.assertFormError(r, "form", "captcha", ugettext_lazy("Invalid CAPTCHA"))

        settings.CAPTCHA_TEST_MODE = True
        # Test mode, only 'PASSED' is accepted
        r = self.client.get(reverse("captcha-test"))
        self.assertEqual(r.status_code, 200)
        r = self.client.post(
            reverse("captcha-test"),
            dict(captcha_0="abc", captcha_1="wrong response", subject="xxx", sender="*****@*****.**"),
        )
        self.assertFormError(r, "form", "captcha", ugettext_lazy("Invalid CAPTCHA"))

        r = self.client.get(reverse("captcha-test"))
        self.assertEqual(r.status_code, 200)
        r = self.client.post(
            reverse("captcha-test"), dict(captcha_0="abc", captcha_1="passed", subject="xxx", sender="*****@*****.**")
        )
        self.assertTrue(str(r.content).find("Form validated") > 0)
        settings.CAPTCHA_TEST_MODE = __current_test_mode_setting
Exemple #8
0
 def __init__(self):
     super(AvgTraffic, self).__init__(
         sent={'type': 'AREA', 'color': '#00FF00',
               "legend": ugettext_lazy("sent messages")},
         recv={"type": "AREA", "color": "#0000FF",
               "legend": ugettext_lazy("received messages")}
     )
Exemple #9
0
 def __init__(self):
     super(AvgBadTraffic, self).__init__(
         bounced={'type': 'AREA', 'color': '#FFFF00',
                  "legend": ugettext_lazy("bounced messages")},
         reject={"type": "AREA", "color": "#FF0000",
                 "legend": ugettext_lazy("rejected messages")}
     )
Exemple #10
0
 def __init__(self, attrs=None):
     choices = (
         ('1', ugettext_lazy('Unknown')),
         ('2', ugettext_lazy('Yes')),
         ('3', ugettext_lazy('No')),
     )
     super(NullBooleanSelect, self).__init__(attrs, choices)
def devilry_verbosenumber(value, number):
    """
    Numbers from 1 to 10 is given as verbose(first, second, third, ...)
    and all numbers above 10 has the number and the corresponding ending(11th, 23rd, 32nd, 41st, ...)

    Args:
        value: The value passed(empty in this case).
        number: To get the verbose version of.

    Returns:
        str: Verbose version of number.
    """
    numbers = {
        1: ugettext_lazy('first'),
        2: ugettext_lazy('second'),
        3: ugettext_lazy('third'),
        4: ugettext_lazy('fourth'),
        5: ugettext_lazy('fifth'),
        6: ugettext_lazy('sixth'),
        7: ugettext_lazy('seventh'),
        8: ugettext_lazy('eighth'),
        9: ugettext_lazy('ninth'),
        10: ugettext_lazy('tenth')
    }

    if number <= 10:
        # use numbers dictionary
        # to get verbose result
        return numbers[number]
    return '{}.'.format(number)
Exemple #12
0
        def _recur(d):
            cur = 0
            ret = ''

            while cur < len(d):

                if type(d[cur]) == list:
                    if d[cur][0] != None:
                        ret += ' <b>' + text(
                            ugettext_lazy(d[cur][0])).upper() + '</b> '
                    ret += '(' + _recur(d[cur][1:]) + ')'
                else:
                    f = registry.get_field_by_name(d[cur]['field'])

                    impacts_query = f.impacts_query(
                        d[cur]['operator'], d[cur]['value'])

                    value = f.value_for_description(d[cur]['value'])

                    if impacts_query:

                        if 'prev_op' in d[cur] and d[cur]['prev_op'] != None:
                            tmp = d[cur]['prev_op']
                            ret += ' <b>' + text(
                                ugettext_lazy(tmp)).upper() + '</b> '


                        ret += '%s %s %s' % (d[cur]['field'].lower(),
                                             d[cur]['operator'],
                                             value)

                cur += 1

            return ret
Exemple #13
0
 def save_object(self, form, commit=True):
     comment = super(ExaminerFeedbackView, self).save_object(form=form)
     if comment.feedback_set.grading_published_datetime is not None:
         messages.warning(self.request, ugettext_lazy('Feedback is already published!'))
     else:
         if 'examiner_add_comment_to_feedback_draft' in self.request.POST:
             # If comment is part of a draft, the comment should only be visible to
             # the examiner until draft-publication.
             comment.visibility = group_models.GroupComment.VISIBILITY_PRIVATE
             comment.part_of_grading = True
             comment = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
         elif 'examiner_publish_feedback' in self.request.POST:
             result, error_msg = comment.feedback_set.publish(
                     published_by=comment.user,
                     grading_points=form.get_grading_points())
             if result is False:
                 messages.error(self.request, ugettext_lazy(error_msg))
             elif len(comment.text) > 0:
                 # Don't make comment visible to others unless it actually
                 # contains any text.
                 comment.visibility = group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE
                 comment.part_of_grading = True
                 comment.published_datetime = comment.get_published_datetime()
                 comment = super(ExaminerFeedbackView, self).save_object(form=form, commit=True)
     return comment
Exemple #14
0
 def clean(self):
     cleaned_data = self.cleaned_data
     # make sure usage or password OR OpenID
     if cleaned_data['password'] and 'openid_url' in cleaned_data and cleaned_data['openid_url']:
         msg = ugettext_lazy(u"Password and OpenID are filled, you should choose between the two authentification modes")
         self._errors["password"] = ErrorList([msg])
         del cleaned_data["password"]
         self._errors["openid_url"] = ErrorList([msg])
         del cleaned_data["openid_url"]
         
     elif cleaned_data['password'] or cleaned_data['password2']:            
         password = cleaned_data['password']
         password2 = cleaned_data['password2']
         if password != password2:
             msg = ugettext_lazy(_(u'Passwords do not match, please check.'))
             self._errors["password"] = ErrorList([msg])
             del cleaned_data["password"]
     else:
         if 'openid_url' not in cleaned_data or not cleaned_data['openid_url']:
             msg = ugettext_lazy(u"Please fill in the passwords")
             self._errors["password"] = ErrorList([msg])
             del cleaned_data["password"]                
             if settings.OPENID:
                 msg = ugettext_lazy(u"Please fill in the OpenID url (or the passwords above)")
                 if 'openid_url' not in self._errors: 
                     self._errors["openid_url"] = ErrorList([msg])
                 try:
                     del cleaned_data["openid_url"]
                 except:
                     pass
     return cleaned_data
Exemple #15
0
        def _recur(d):
            cur = 0
            ret = u''

            while cur < len(d):

                if type(d[cur]) == list:
                    if d[cur][0] != None:
                        ret += u' <b>' + unicode(
                            ugettext_lazy(d[cur][0])).upper() + u'</b> '
                    ret += u'(' + _recur(d[cur][1:]) + u')'
                else:
                    if d[cur].has_key('prev_op') and d[cur]['prev_op'] != None:
                        ret += u' <b>' + unicode(
                            ugettext_lazy(d[cur]['prev_op'])).upper() + u'</b> '

                    value = d[cur]['value']

                    f = registry.get_field_by_name(d[cur]['field'])
                    value = f.value_for_description(value)

                    ret += '%s %s %s' % (d[cur]['field'].lower(),
                                         d[cur]['operator'],
                                         value)

                cur += 1

            return ret
def extra_parameters(app, level):
    if app != 'modoboa_admin_limits' or level != 'A':
        return {}
    return {
        'deflt_relay_domains_limit': forms.IntegerField(
            label=ugettext_lazy("Relay domains"),
            initial=0,
            help_text=ugettext_lazy(
                "Maximum number of allowed relay domains for a new "
                "administrator"
            ),
            widget=forms.widgets.TextInput(
                attrs={
                    "class": "col-md-1 form-control"})
        ),
        'deflt_relay_domain_aliases_limit': forms.IntegerField(
            label=ugettext_lazy("Relay domain aliases"),
            initial=0,
            help_text=ugettext_lazy(
                "Maximum number of allowed relay domain aliases for a new "
                "administrator"
            ),
            widget=forms.widgets.TextInput(
                attrs={
                    "class": "col-md-1 form-control"})
        )
    }
Exemple #17
0
    def __init__(self,
                 *,
                 choices=None,
                 widget=None,
                 initial=None,
                 label=None,
                 doc='',
                 **kwargs):
        # 2015-1-19: why is this here? isn't this the default behavior?
        # 2013-1-26: ah, because we don't want the "----" (None) choice
        if choices is None:
            choices = (
                (True, ugettext_lazy('Yes')),
                (False, ugettext_lazy('No'))
            )

        # We need to store whether blank is explicitly specified or not. If
        # it's not specified explicitly (which will make it default to False)
        # we need to special case validation logic in the form field if a
        # checkbox input is used.
        self._blank_is_explicit = 'blank' in kwargs

        kwargs.setdefault('help_text', '')
        kwargs.setdefault('null', True)

        super().__init__(
            choices=choices,
            widget=widget,
            initial=initial,
            label=label,
            doc=doc,
            **kwargs)

        # you cant override "blank" or you will destroy the migration system
        self.allow_blank = bool(kwargs.get("blank"))
 def get_subject_text(self):
     """
     Get a standard subject text based on the role of the comment poster.
     """
     if self.is_receipt:
         after_deadline = self.comment.published_datetime > self.comment.feedback_set.deadline_datetime
         if after_deadline:
             subject_text = ugettext_lazy('You added a new comment AFTER THE DEADLINE for %(assignment_name)s') % {
                 'assignment_name': self.comment.feedback_set.group.parentnode.long_name
             }
         else:
             subject_text = ugettext_lazy('You added a new delivery/comment for %(assignment_name)s') % {
                 'assignment_name': self.comment.feedback_set.group.parentnode.long_name
             }
         return subject_text
     if self.comment.user_role == Comment.USER_ROLE_STUDENT:
         if self.comment.published_datetime > self.comment.feedback_set.deadline_datetime:
             return ugettext('A student added a new comment AFTER THE DEADLINE for %(assignment_name)s') % {
                 'assignment_name': self.comment.feedback_set.group.parentnode.long_name
             }
         return ugettext('A student added a new delivery/comment for %(assignment_name)s') % {
             'assignment_name': self.comment.feedback_set.group.parentnode.long_name
         }
     elif self.comment.user_role == Comment.USER_ROLE_EXAMINER:
         return ugettext('An examiner added a new comment for %(assignment_name)s') % {
             'assignment_name': self.comment.feedback_set.group.parentnode.long_name
         }
     return ugettext('An admin added a new comment for %(assignment_name)s') % {
         'assignment_name': self.comment.feedback_set.group.parentnode.long_name
     }
Exemple #19
0
 def __init__(self, **kwargs):
     XferContainerCustom.__init__(self, **kwargs)
     self.fieldnames = None
     self.action_list = [('listing', ugettext_lazy("Listing"), "images/print.png"),
                         ('label', ugettext_lazy("Label"), "images/print.png")]
     self.action_grid = deepcopy(DEFAULT_ACTION_LIST)
     self.filter = None
Exemple #20
0
 def upgrade(self):
     self.btnupgrade.config(state=DISABLED)
     self.instance_list.config(state=DISABLED)
     try:
         from logging import getLogger
         admin_path = import_module(
             "lucterios.install.lucterios_admin").__file__
         proc = Popen(
             [sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE)
         value = proc.communicate()[0]
         try:
             value = value.decode('ascii')
         except Exception:
             pass
         six.print_(value)
         if proc.returncode != 0:
             getLogger("lucterios.admin").error(value)
         else:
             getLogger("lucterios.admin").info(value)
         showinfo(ugettext_lazy("Lucterios launcher"), ugettext_lazy(
             "The application must restart"))
         python = sys.executable
         os.execl(python, python, *sys.argv)
     finally:
         self._refresh_modules()
         self.btnupgrade.config(state=NORMAL)
         self.instance_list.config(state=NORMAL)
Exemple #21
0
    def __init__(self):
        # These two lines make sure translation identifies these strings
        name = ugettext_lazy(u'FirstMKFollow')._proxy__args[0]
        description = ugettext_lazy(u'You are following an MK')._proxy__args[0]

        super(FirstFollowHandler, self).__init__(
            badge_name=name, badge_description=description)
Exemple #22
0
    def _refresh_modules(self):
        self.btnupgrade.config(state=DISABLED)
        self.module_txt.config(state=NORMAL)
        self.module_txt.delete("1.0", END)
        lct_glob = LucteriosGlobal()
        mod_lucterios, mod_applis, mod_modules = lct_glob.installed()
        self.module_txt.insert(
            END, ugettext_lazy("Lucterios core\t\t%s\n") % mod_lucterios[1])
        self.module_txt.insert(END, '\n')
        self.module_txt.insert(END, ugettext_lazy("Application\n"))
        for appli_item in mod_applis:
            self.module_txt.insert(
                END, "\t%s\t%s\n" % (appli_item[0].ljust(30), appli_item[1]))
        self.module_txt.insert(END, ugettext_lazy("Modules\n"))
        for module_item in mod_modules:
            self.module_txt.insert(
                END, "\t%s\t%s\n" % (module_item[0].ljust(30), module_item[1]))
        extra_urls = lct_glob.get_extra_urls()
        if len(extra_urls) > 0:
            self.module_txt.insert(END, "\n")
            self.module_txt.insert(END, ugettext_lazy("Pypi servers\n"))
            for extra_url in extra_urls:
                self.module_txt.insert(END, "\t%s\n" % extra_url)
        self.module_txt.config(state=DISABLED)
        self.has_checked = True

        self.after(1000, lambda: Thread(target=self.check).start())
Exemple #23
0
def get_edit_handler(cls):
    """
    Get the EditHandler to use in the Wagtail admin when editing this page type.
    """
    if hasattr(cls, 'edit_handler'):
        edit_handler = cls.edit_handler
    else:
        # construct a TabbedInterface made up of content_panels, promote_panels
        # and settings_panels, skipping any which are empty
        tabs = []

        if cls.content_panels:
            tabs.append(ObjectList(cls.content_panels,
                                   heading=ugettext_lazy('Content')))
        if cls.promote_panels:
            tabs.append(ObjectList(cls.promote_panels,
                                   heading=ugettext_lazy('Promote')))
        if cls.settings_panels:
            tabs.append(ObjectList(cls.settings_panels,
                                   heading=ugettext_lazy('Settings'),
                                   classname='settings'))

        edit_handler = TabbedInterface(tabs, base_form_class=cls.base_form_class)

    return edit_handler.bind_to(model=cls)
Exemple #24
0
    def __init__(self, domain, *args, **kwargs):
        super(AppTranslationsForm, self).__init__(*args, **kwargs)
        self.domain = domain
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.label_class = 'col-sm-4 col-md-4 col-lg-3'
        self.helper.field_class = 'col-sm-6 col-md-6 col-lg-5'

        self.fields['app_id'].choices = tuple((app.id, app.name) for app in get_brief_apps_in_domain(domain))
        projects = TransifexProject.objects.filter(domain=domain).all()
        if projects:
            self.fields['transifex_project_slug'].choices = (
                tuple((project.slug, project) for project in projects)
            )
        form_fields = self.form_fields()
        form_fields.append(hqcrispy.Field(StrictButton(
            ugettext_lazy("Submit"),
            type="submit",
            css_class="btn btn-primary btn-lg disable-on-submit",
            onclick="return confirm('%s')" % ugettext_lazy("Please confirm that you want to proceed?")
        )))
        self.helper.layout = crispy.Layout(
            *form_fields
        )
        self.fields['action'].initial = self.form_action
Exemple #25
0
def vote_tag(request, tag):
    tag_instance = get_tag(tag)
    if tag_instance is None:
        raise Http404(_('No Tag found matching "%s".') % tag)        
    
    extra_context = {'tag':tag_instance}
    extra_context['tag_url'] = reverse('vote-tag',args=[tag_instance])
    if 'member' in request.GET: 
        extra_context['member'] = get_object_or_404(Member, pk=request.GET['member'])
        extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id])
        extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name}
        qs = extra_context['member'].votes.all()
    else: # only tag is given
        extra_context['title'] = ugettext_lazy('Votes tagged %(tag)s') % {'tag': tag}
        qs = Vote

    queryset = TaggedItem.objects.get_by_model(qs, tag_instance)
    vote_attendence = [v.votes.all() for v in TaggedItem.objects.get_by_model(Vote, tag_instance)]
    d = {}
    for vote in vote_attendence:
        for v in vote:
            d[v] = d.get(v,0)+1
    # now d is a dict: MK -> number of votes in this tag
    mks = d.keys()    
    for mk in mks:
        mk.count = d[mk]
    average = float(sum([mk.count for mk in mks]))/len(mks)
    mks = [mk for mk in mks if mk.count>=average]
    mks = tagging.utils.calculate_cloud(mks)
    extra_context['members'] = mks
    return object_list(request, queryset,
    #return tagged_object_list(request, queryset_or_model=qs, tag=tag, 
        template_name='laws/vote_list_by_tag.html', extra_context=extra_context)
 def form_valid(self, form):
     try:
         candidates = Candidate.objects.filter(id__in=json.loads(form.data['candidates']))\
             .select_related('relatedstudent__user')
         self.util_class.set_passed_in_current_period(
             candidates,
             self.request.user
         )
     except SomeCandidatesDoesNotQualifyToPass as e:
         messages.warning(
             self.request,
             ugettext_lazy('Some students does not qualify to pass the assignment.')
         )
     except NoCandidatesPassed:
         messages.warning(
             self.request,
             ugettext_lazy('No students are qualified to get approved '
                           'for this assignment from a previous assignment.')
         )
     except:
         messages.warning(
             self.request,
             ugettext_lazy('An error occurred.')
         )
     else:
         messages.success(
             self.request,
             ugettext_lazy(
                 '%(students)s was marked as approved for this assignment.') % {
                 'students': self.__get_candidates_displayname(candidates)
             }
         )
     return redirect(self.get_success_url())
Exemple #27
0
    def send_invite_notification(self, request):
        """
        Called to send the invite notification. Should be called
        right after creating the invite. Not called in save() to
        make message sending less coupled (to avoid any issues
        with testing and bulk creation of invites).

        Args:
            request:
                A Django HttpRequest object. The only method used is
                the build_absolute_uri() method.

        Raises:
            ValueError If ``accepted==None``, or ``id==None``.

        """
        if self.accepted is not None:
            raise ValueError(ugettext_lazy('Can not send notification for an accepted GroupInvite.'))
        elif self.id is None:
            raise ValueError(ugettext_lazy('Can not send notification for an unsaved GroupInvite.'))
        sent_by_displayname = self.sent_by.get_displayname()
        assignment = self.group.assignment
        subject = ugettext_lazy('Project group invite for {assignment}').format(assignment=assignment.get_path())
        template_name = 'devilry_core/groupinvite_invite.django.txt'
        url = request.build_absolute_uri(reverse('devilry_student_groupinvite_respond', kwargs={'invite_id': self.id}))
        send_templated_message(subject, template_name, {
            'sent_by_displayname': sent_by_displayname,
            'assignment': assignment.long_name,
            'subject': assignment.subject.long_name,
            'url': url
        }, self.sent_to)
Exemple #28
0
    def __init__(self):
        Toplevel.__init__(self)
        self.name_rull = compile("[a-z0-9_\-]+")
        self.is_new_instance = True
        self.focus_set()
        self.grab_set()

        self.result = None
        self.module_data = None
        self.mod_applis = None
        self.title(ugettext_lazy("Instance editor"))
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.ntbk = ttk.Notebook(self)
        self.ntbk.grid(row=0, column=0, columnspan=1, sticky=(N, S, E, W))

        self.frm_general = Frame(self.ntbk, width=350, height=150)
        self.frm_general.grid_columnconfigure(0, weight=0)
        self.frm_general.grid_columnconfigure(1, weight=1)
        self._general_tabs()
        self.ntbk.add(self.frm_general, text=ugettext_lazy('General'))

        self.frm_database = Frame(self.ntbk, width=350, height=150)
        self.frm_database.grid_columnconfigure(0, weight=0)
        self.frm_database.grid_columnconfigure(1, weight=1)
        self._database_tabs()
        self.ntbk.add(self.frm_database, text=ugettext_lazy('Database'))

        btnframe = Frame(self, bd=1)
        btnframe.grid(row=1, column=0, columnspan=1)
        Button(btnframe, text=ugettext_lazy("OK"), width=10, command=self.apply).grid(
            row=0, column=0, sticky=(N, S, E))
        Button(btnframe, text=ugettext_lazy("Cancel"), width=10, command=self.destroy).grid(
            row=0, column=1, sticky=(N, S, W))
Exemple #29
0
def bill_tag(request, tag):
    tag_instance = get_tag(tag)
    if tag_instance is None:
        raise Http404(_('No Tag found matching "%s".') % tag)        
    
    extra_context = {'tag':tag_instance}
    extra_context['tag_url'] = reverse('bill-tag',args=[tag_instance])
    if 'member' in request.GET: 
        extra_context['member'] = get_object_or_404(Member, pk=request.GET['member'])
        extra_context['member_url'] = reverse('member-detail',args=[extra_context['member'].id])
        extra_context['title'] = ugettext_lazy('Bills tagged %(tag)s by %(member)s') % {'tag': tag, 'member':extra_context['member'].name}
        qs = extra_context['member'].bills.all()
    else: # only tag is given
        extra_context['title'] = ugettext_lazy('Bills tagged %(tag)s') % {'tag': tag}
        qs = Bill

    queryset = TaggedItem.objects.get_by_model(qs, tag_instance)
    bill_proposers = [b.proposers.all() for b in TaggedItem.objects.get_by_model(Bill, tag_instance)]
    d = {}
    for bill in bill_proposers:
        for p in bill:
            d[p] = d.get(p,0)+1
    # now d is a dict: MK -> number of proposals in this tag
    mks = d.keys()
    for mk in mks:
        mk.count = d[mk]
    mks = tagging.utils.calculate_cloud(mks)
    extra_context['members'] = mks
    return object_list(request, queryset,
    #return tagged_object_list(request, queryset_or_model=qs, tag=tag, 
        template_name='laws/bill_list_by_tag.html', extra_context=extra_context)
Exemple #30
0
 def set_ugrade_state(self, must_upgrade):
     if must_upgrade:
         self.btnupgrade.config(state=NORMAL)
         self.btnupgrade["text"] = ugettext_lazy("Upgrade needs")
     else:
         self.btnupgrade["text"] = ugettext_lazy("No upgrade")
         self.btnupgrade.config(state=DISABLED)
Exemple #31
0
class SettingsForm(Form):
    # General Settings
    use_default_sms_response = ChoiceField(
        required=False,
        label=ugettext_noop("Default SMS Response"),
        choices=ENABLED_DISABLED_CHOICES,
    )
    default_sms_response = TrimmedCharField(
        required=False,
        label="",
    )
    use_restricted_sms_times = ChoiceField(
        required=False,
        label=ugettext_noop("Send SMS on..."),
        choices=(
            (DISABLED, ugettext_noop("any day, at any time")),
            (ENABLED, ugettext_noop("only specific days and times")),
        ),
    )
    restricted_sms_times_json = CharField(
        required=False,
        widget=forms.HiddenInput,
    )
    send_to_duplicated_case_numbers = ChoiceField(
        required=False,
        label=ugettext_noop("Send Messages to Non-Unique Phone Numbers"),
        choices=ENABLED_DISABLED_CHOICES,
    )

    sms_survey_date_format = ChoiceField(
        required=False,
        label=ugettext_lazy("SMS Survey Date Format"),
        choices=((df.human_readable_format,
                  ugettext_lazy(df.human_readable_format))
                 for df in ALLOWED_SURVEY_DATE_FORMATS),
    )

    # Chat Settings
    use_custom_case_username = ChoiceField(
        required=False,
        choices=DEFAULT_CUSTOM_CHOICES,
    )
    custom_case_username = TrimmedCharField(
        required=False,
        label=ugettext_noop("Enter a Case Property"),
    )
    use_custom_message_count_threshold = ChoiceField(
        required=False,
        choices=MESSAGE_COUNTER_CHOICES,
    )
    custom_message_count_threshold = IntegerField(
        required=False,
        label=ugettext_noop("Enter a Number"),
    )
    use_sms_conversation_times = ChoiceField(
        required=False,
        label=ugettext_noop("Delay Automated SMS"),
        choices=ENABLED_DISABLED_CHOICES,
    )
    sms_conversation_times_json = CharField(
        required=False,
        widget=forms.HiddenInput,
    )
    sms_conversation_length = ChoiceField(
        required=False,
        label=ugettext_noop("Conversation Duration"),
        choices=SMS_CONVERSATION_LENGTH_CHOICES,
    )
    survey_traffic_option = ChoiceField(
        required=False,
        label=ugettext_noop("Survey Traffic"),
        choices=(
            (SHOW_ALL, ugettext_noop("Show all survey traffic")),
            (SHOW_INVALID,
             ugettext_noop("Hide all survey traffic except "
                           "invalid responses")),
            (HIDE_ALL, ugettext_noop("Hide all survey traffic")),
        ),
    )
    count_messages_as_read_by_anyone = ChoiceField(
        required=False,
        label=ugettext_noop("A Message is Read..."),
        choices=(
            (ENABLED, ugettext_noop("when it is read by anyone")),
            (DISABLED, ugettext_noop("only for the user that reads it")),
        ),
    )
    use_custom_chat_template = ChoiceField(
        required=False,
        choices=DEFAULT_CUSTOM_CHOICES,
    )
    custom_chat_template = TrimmedCharField(
        required=False,
        label=ugettext_noop("Enter Chat Template Identifier"),
    )

    # Registration settings
    sms_case_registration_enabled = ChoiceField(
        required=False,
        choices=ENABLED_DISABLED_CHOICES,
        label=ugettext_noop("Case Self-Registration"),
    )
    sms_case_registration_type = TrimmedCharField(
        required=False,
        label=ugettext_noop("Default Case Type"),
    )
    sms_case_registration_owner_id = ChoiceField(
        required=False,
        label=ugettext_noop("Default Case Owner"),
    )
    sms_case_registration_user_id = ChoiceField(
        required=False,
        label=ugettext_noop("Registration Submitter"),
    )
    sms_mobile_worker_registration_enabled = ChoiceField(
        required=False,
        choices=ENABLED_DISABLED_CHOICES,
        label=ugettext_noop("SMS Mobile Worker Registration"),
    )
    registration_welcome_message = ChoiceField(
        choices=WELCOME_RECIPIENT_CHOICES,
        label=ugettext_lazy("Send registration welcome message to"),
    )

    @property
    def section_general(self):
        fields = [
            hqcrispy.B3MultiField(
                _("Default SMS Response"),
                crispy.Div(InlineField(
                    "use_default_sms_response",
                    data_bind="value: use_default_sms_response",
                ),
                           css_class='col-sm-4'),
                crispy.Div(InlineField(
                    "default_sms_response",
                    css_class="input-xxlarge",
                    placeholder=_("Enter Default Response"),
                    data_bind="visible: showDefaultSMSResponse",
                ),
                           css_class='col-sm-8'),
                help_bubble_text=_(
                    "Enable this option to provide a "
                    "default response when a user's incoming SMS does not "
                    "answer an open survey or match a known keyword."),
                css_id="default-sms-response-group",
                field_class='col-sm-6 col-md-9 col-lg-9'),
            FieldWithHelpBubble(
                "use_restricted_sms_times",
                data_bind="value: use_restricted_sms_times",
                help_bubble_text=_(
                    "Use this option to limit the times "
                    "that SMS messages can be sent to users. Messages that "
                    "are sent outside these windows will remained queued "
                    "and will go out as soon as another window opens up."),
            ),
            hqcrispy.B3MultiField(
                "",
                HiddenFieldWithErrors(
                    "restricted_sms_times_json",
                    data_bind="value: restricted_sms_times_json"),
                crispy.Div(data_bind="template: {"
                           " name: 'ko-template-restricted-sms-times', "
                           " data: $data"
                           "}", ),
                data_bind="visible: showRestrictedSMSTimes",
                field_class='col-md-10 col-lg-10'),
            FieldWithHelpBubble(
                "send_to_duplicated_case_numbers",
                help_bubble_text=_(
                    "Enabling this option will send "
                    "outgoing-only messages to phone numbers registered "
                    "with more than one mobile worker or case. SMS surveys "
                    "and keywords will still only work for unique phone "
                    "numbers in your project."),
            ),
            FieldWithHelpBubble(
                'sms_survey_date_format',
                help_bubble_text=_("Choose the format in which date questions "
                                   "should be answered in SMS surveys."),
            ),
        ]
        return crispy.Fieldset(_("General Settings"), *fields)

    @property
    def section_registration(self):
        fields = [
            FieldWithHelpBubble(
                "sms_case_registration_enabled",
                help_bubble_text=_(
                    "When this option is enabled, a person "
                    "can send an SMS into the system saying 'join "
                    "[project]', where [project] is your project "
                    "space name, and the system will automatically "
                    "create a case tied to that person's phone number."),
                data_bind="value: sms_case_registration_enabled",
            ),
            crispy.Div(
                FieldWithHelpBubble(
                    "sms_case_registration_type",
                    placeholder=_("Enter a Case Type"),
                    help_bubble_text=_("Cases that self-register over SMS "
                                       "will be given this case type."),
                ),
                FieldWithHelpBubble(
                    "sms_case_registration_owner_id",
                    help_bubble_text=_(
                        "Cases that self-register over SMS "
                        "will be owned by this user or user group."),
                ),
                FieldWithHelpBubble(
                    "sms_case_registration_user_id",
                    help_bubble_text=_(
                        "The form submission for a "
                        "self-registration will belong to this user."),
                ),
                data_bind="visible: showRegistrationOptions",
            ),
            FieldWithHelpBubble(
                "sms_mobile_worker_registration_enabled",
                help_bubble_text=_(
                    "When this option is enabled, a person "
                    "can send an SMS into the system saying 'join "
                    "[project] worker [username]' (where [project] is your "
                    " project space and [username] is an optional username)"
                    ", and the system will add them as a mobile worker."),
            ),
            FieldWithHelpBubble(
                'registration_welcome_message',
                help_bubble_text=_(
                    "Choose whether to send an automatic "
                    "welcome message to cases, mobile workers, or both, "
                    "after they self-register. The welcome message can be "
                    "configured in the SMS languages and translations page "
                    "(Messaging -> Languages -> Messaging Translations)."),
            ),
        ]
        return crispy.Fieldset(_("Registration Settings"), *fields)

    @property
    def section_chat(self):
        fields = [
            hqcrispy.B3MultiField(
                _("Case Name Display"),
                crispy.Div(InlineField(
                    "use_custom_case_username",
                    data_bind="value: use_custom_case_username",
                ),
                           css_class='col-sm-4'),
                crispy.Div(InlineField(
                    "custom_case_username",
                    css_class="input-large",
                    data_bind="visible: showCustomCaseUsername",
                ),
                           css_class='col-sm-8'),
                help_bubble_text=_(
                    "By default, when chatting with a case, "
                    "the chat window will use the case's \"name\" case "
                    "property when displaying the case's name. To use a "
                    "different case property, specify it here."),
                css_id="custom-case-username-group",
                field_class='col-sm-6 col-md-9 col-lg-9'),
            hqcrispy.B3MultiField(
                _("Message Counter"),
                crispy.Div(InlineField(
                    "use_custom_message_count_threshold",
                    data_bind="value: use_custom_message_count_threshold",
                ),
                           css_class='col-sm-4'),
                crispy.Div(InlineField(
                    "custom_message_count_threshold",
                    css_class="input-large",
                    data_bind="visible: showCustomMessageCountThreshold",
                ),
                           css_class='col-sm-8'),
                help_bubble_text=_(
                    "The chat window can use a counter to keep "
                    "track of how many messages are being sent and received "
                    "and highlight that number after a certain threshold is "
                    "reached. By default, the counter is disabled. To enable "
                    "it, enter the desired threshold here."),
                css_id="custom-message-count-threshold-group",
                field_class='col-sm-6 col-md-9 col-lg-9'),
            FieldWithHelpBubble(
                "use_sms_conversation_times",
                data_bind="value: use_sms_conversation_times",
                help_bubble_text=_(
                    "When this option is enabled, the system "
                    "will not send automated SMS to chat recipients when "
                    "those recipients are in the middle of a conversation."),
            ),
            hqcrispy.B3MultiField(
                "",
                HiddenFieldWithErrors(
                    "sms_conversation_times_json",
                    data_bind="value: sms_conversation_times_json"),
                crispy.Div(data_bind="template: {"
                           " name: 'ko-template-sms-conversation-times', "
                           " data: $data"
                           "}", ),
                data_bind="visible: showSMSConversationTimes",
                label_class='hide',
                field_class='col-md-12 col-lg-10'),
            crispy.Div(
                FieldWithHelpBubble(
                    "sms_conversation_length",
                    help_bubble_text=_(
                        "The number of minutes to wait "
                        "after receiving an incoming SMS from a chat "
                        "recipient before resuming automated SMS to that "
                        "recipient."),
                ),
                data_bind="visible: showSMSConversationTimes",
            ),
            FieldWithHelpBubble(
                "survey_traffic_option",
                help_bubble_text=_(
                    "This option allows you to hide a chat "
                    "recipient's survey questions and responses from chat "
                    "windows. There is also the option to show only invalid "
                    "responses to questions in the chat window, which could "
                    "be attempts to converse."),
            ),
            FieldWithHelpBubble(
                "count_messages_as_read_by_anyone",
                help_bubble_text=_(
                    "The chat window will mark unread "
                    "messages to the user viewing them. Use this option to "
                    "control whether a message counts as being read if it "
                    "is read by anyone, or if it counts as being read only "
                    "to the user who reads it."),
            ),
        ]
        if self._cchq_is_previewer:
            fields.append(
                hqcrispy.B3MultiField(
                    _("Chat Template"),
                    crispy.Div(InlineField(
                        "use_custom_chat_template",
                        data_bind="value: use_custom_chat_template",
                    ),
                               css_class='col-sm-4'),
                    crispy.Div(InlineField(
                        "custom_chat_template",
                        data_bind="visible: showCustomChatTemplate",
                    ),
                               css_class='col-sm-8'),
                    help_bubble_text=_(
                        "To use a custom template to render the "
                        "chat window, enter it here."),
                    css_id="custom-chat-template-group",
                    field_class='col-sm-6 col-md-9 col-lg-9'))
        return crispy.Fieldset(_("Chat Settings"), *fields)

    def __init__(self,
                 data=None,
                 cchq_domain=None,
                 cchq_is_previewer=False,
                 *args,
                 **kwargs):
        self._cchq_domain = cchq_domain
        self._cchq_is_previewer = cchq_is_previewer
        super(SettingsForm, self).__init__(data, *args, **kwargs)
        self.populate_dynamic_choices()

        self.helper = FormHelper()
        self.helper.form_class = "form form-horizontal"
        self.helper.label_class = 'col-sm-2 col-md-2 col-lg-2'
        self.helper.field_class = 'col-sm-2 col-md-3 col-lg-3'
        self.helper.layout = crispy.Layout(
            self.section_general,
            self.section_registration,
            self.section_chat,
            hqcrispy.FormActions(
                twbscrispy.StrictButton(
                    _("Save"),
                    type="submit",
                    css_class="btn-primary",
                ), ),
        )
        self.restricted_sms_times_widget_context = {
            "template_name":
            "ko-template-restricted-sms-times",
            "explanation_text":
            _("SMS will only be sent when any of the following is true:"),
            "ko_array_name":
            "restricted_sms_times",
            "remove_window_method":
            "$parent.removeRestrictedSMSTime",
            "add_window_method":
            "addRestrictedSMSTime",
        }
        self.sms_conversation_times_widget_context = {
            "template_name":
            "ko-template-sms-conversation-times",
            "explanation_text":
            _("Automated SMS will be suppressed during "
              "chat conversations when any of the following "
              "is true:"),
            "ko_array_name":
            "sms_conversation_times",
            "remove_window_method":
            "$parent.removeSMSConversationTime",
            "add_window_method":
            "addSMSConversationTime",
        }

    @property
    def enable_registration_welcome_sms_for_case(self):
        return (self.cleaned_data.get('registration_welcome_message')
                in (WELCOME_RECIPIENT_CASE, WELCOME_RECIPIENT_ALL))

    @property
    def enable_registration_welcome_sms_for_mobile_worker(self):
        return (self.cleaned_data.get('registration_welcome_message')
                in (WELCOME_RECIPIENT_MOBILE_WORKER, WELCOME_RECIPIENT_ALL))

    @property
    def current_values(self):
        current_values = {}
        for field_name in self.fields.keys():
            value = self[field_name].value()
            if field_name in [
                    "restricted_sms_times_json", "sms_conversation_times_json"
            ]:
                if isinstance(value, basestring):
                    current_values[field_name] = json.loads(value)
                else:
                    current_values[field_name] = value
            else:
                current_values[field_name] = value
        return current_values

    def populate_dynamic_choices(self):
        groups = Group.get_case_sharing_groups(self._cchq_domain)
        users = CommCareUser.by_domain(self._cchq_domain)

        domain_group_choices = [(group._id, group.name) for group in groups]
        domain_user_choices = [(user._id, user.raw_username) for user in users]
        domain_owner_choices = domain_group_choices + domain_user_choices

        choose = [("", _("(Choose)"))]
        self.fields["sms_case_registration_owner_id"].choices = (
            choose + domain_owner_choices)
        self.fields["sms_case_registration_user_id"].choices = (
            choose + domain_user_choices)

    def _clean_dependent_field(self, bool_field, field):
        if self.cleaned_data.get(bool_field):
            value = self.cleaned_data.get(field, None)
            if not value:
                raise ValidationError(_("This field is required."))
            return value
        else:
            return None

    def clean_use_default_sms_response(self):
        return self.cleaned_data.get("use_default_sms_response") == ENABLED

    def clean_default_sms_response(self):
        return self._clean_dependent_field("use_default_sms_response",
                                           "default_sms_response")

    def clean_use_custom_case_username(self):
        return self.cleaned_data.get("use_custom_case_username") == CUSTOM

    def clean_custom_case_username(self):
        return self._clean_dependent_field("use_custom_case_username",
                                           "custom_case_username")

    def clean_use_custom_message_count_threshold(self):
        return (self.cleaned_data.get("use_custom_message_count_threshold") ==
                CUSTOM)

    def clean_custom_message_count_threshold(self):
        value = self._clean_dependent_field(
            "use_custom_message_count_threshold",
            "custom_message_count_threshold")
        if value is not None and value <= 0:
            raise ValidationError(_("Please enter a positive number"))
        return value

    def clean_use_custom_chat_template(self):
        if not self._cchq_is_previewer:
            return None
        return self.cleaned_data.get("use_custom_chat_template") == CUSTOM

    def clean_custom_chat_template(self):
        if not self._cchq_is_previewer:
            return None
        value = self._clean_dependent_field("use_custom_chat_template",
                                            "custom_chat_template")
        if value is not None and value not in settings.CUSTOM_CHAT_TEMPLATES:
            raise ValidationError(_("Unknown custom template identifier."))
        return value

    def _clean_time_window_json(self, field_name):
        try:
            time_window_json = json.loads(self.cleaned_data.get(field_name))
        except ValueError:
            raise ValidationError(
                _("An error has occurred. Please try again, "
                  "and if the problem persists, please report an issue."))
        result = []
        for window in time_window_json:
            day = window.get("day")
            start_time = window.get("start_time")
            end_time = window.get("end_time")
            time_input_relationship = window.get("time_input_relationship")

            try:
                day = int(day)
                assert day >= -1 and day <= 6
            except (ValueError, AssertionError):
                raise ValidationError(_("Invalid day chosen."))

            if time_input_relationship == TIME_BEFORE:
                end_time = validate_time(end_time)
                result.append(
                    DayTimeWindow(
                        day=day,
                        start_time=None,
                        end_time=end_time,
                    ))
            elif time_input_relationship == TIME_AFTER:
                start_time = validate_time(start_time)
                result.append(
                    DayTimeWindow(
                        day=day,
                        start_time=start_time,
                        end_time=None,
                    ))
            else:
                start_time = validate_time(start_time)
                end_time = validate_time(end_time)
                if start_time >= end_time:
                    raise ValidationError(
                        _("End time must come after start "
                          "time."))
                result.append(
                    DayTimeWindow(
                        day=day,
                        start_time=start_time,
                        end_time=end_time,
                    ))
        return result

    def clean_use_restricted_sms_times(self):
        return self.cleaned_data.get("use_restricted_sms_times") == ENABLED

    def clean_restricted_sms_times_json(self):
        if self.cleaned_data.get("use_restricted_sms_times"):
            return self._clean_time_window_json("restricted_sms_times_json")
        else:
            return []

    def clean_use_sms_conversation_times(self):
        return self.cleaned_data.get("use_sms_conversation_times") == ENABLED

    def clean_sms_conversation_times_json(self):
        if self.cleaned_data.get("use_sms_conversation_times"):
            return self._clean_time_window_json("sms_conversation_times_json")
        else:
            return []

    def clean_send_to_duplicated_case_numbers(self):
        return (self.cleaned_data.get("send_to_duplicated_case_numbers") ==
                ENABLED)

    def clean_count_messages_as_read_by_anyone(self):
        return (self.cleaned_data.get("count_messages_as_read_by_anyone") ==
                ENABLED)

    def clean_sms_case_registration_enabled(self):
        return (
            self.cleaned_data.get("sms_case_registration_enabled") == ENABLED)

    def clean_sms_case_registration_type(self):
        return self._clean_dependent_field("sms_case_registration_enabled",
                                           "sms_case_registration_type")

    def _clean_registration_id_field(self, field_name):
        if self.cleaned_data.get("sms_case_registration_enabled"):
            value = self.cleaned_data.get(field_name)
            if not value:
                raise ValidationError(_("This field is required."))
            # Otherwise, the ChoiceField automatically validates that it is
            # in the list that is dynamically populated in __init__
            return value
        else:
            return None

    def clean_sms_case_registration_owner_id(self):
        return self._clean_registration_id_field(
            "sms_case_registration_owner_id")

    def clean_sms_case_registration_user_id(self):
        return self._clean_registration_id_field(
            "sms_case_registration_user_id")

    def clean_sms_mobile_worker_registration_enabled(self):
        return (self.cleaned_data.get("sms_mobile_worker_registration_enabled")
                == ENABLED)

    def clean_sms_conversation_length(self):
        # Just cast to int, the ChoiceField will validate that it is an integer
        return int(self.cleaned_data.get("sms_conversation_length"))
Exemple #32
0
 class SomeForm(Form):
     field_1 = CharField(max_length=10, label=ugettext_lazy('field_1'))
     field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'}))
Exemple #33
0
 class SomeForm(Form):
     username = CharField(max_length=10, label=ugettext_lazy('Username'))
Exemple #34
0
from django.http import Http404
from django.shortcuts import render
from django.template import RequestContext
from django.utils.translation import ugettext_lazy

import game.messages as messages
import game.permissions as permissions
from game.views.scoreboard_csv import scoreboard_csv
from helper import renderError
from game.forms import ScoreboardForm
from game.models import Level, Attempt, sort_levels
from portal.models import Class, Teacher, Student

Single_Level_Header = [
    ugettext_lazy('Class'),
    ugettext_lazy('Name'),
    ugettext_lazy('Score'),
    ugettext_lazy('Total Time'),
    ugettext_lazy('Start Time'),
    ugettext_lazy('Finish Time')
]
Progress_Header = ugettext_lazy('Progress')
Multiple_Levels_Header = [
    ugettext_lazy('Class'),
    ugettext_lazy('Name'),
    ugettext_lazy('Total Score'),
    ugettext_lazy('Total Time'), Progress_Header
]

from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy

from plinth import actions
from plinth.modules import dynamicdns
from plinth.signals import domain_added, domain_removed

from .forms import ConfigureForm

logger = logging.getLogger(__name__)

EMPTYSTRING = 'none'

subsubmenu = [{
    'url': reverse_lazy('dynamicdns:index'),
    'text': ugettext_lazy('About')
}, {
    'url': reverse_lazy('dynamicdns:configure'),
    'text': ugettext_lazy('Configure')
}, {
    'url': reverse_lazy('dynamicdns:statuspage'),
    'text': ugettext_lazy('Status')
}]


def index(request):
    """Serve Dynamic DNS page."""
    return TemplateResponse(
        request, 'dynamicdns.html', {
            'app_info': dynamicdns.app.info,
            'title': dynamicdns.app.info.name,
Exemple #36
0
class SendRegistrationInvitationsForm(Form):

    PHONE_TYPE_ANDROID_ONLY = 'ANDROID'
    PHONE_TYPE_ANY = 'ANY'

    PHONE_CHOICES = (
        (PHONE_TYPE_ANDROID_ONLY, ugettext_lazy("Android Only")),
        (PHONE_TYPE_ANY, ugettext_lazy("Android or Other")),
    )

    phone_numbers = TrimmedCharField(
        label=ugettext_lazy("Phone Number(s)"),
        required=True,
        widget=forms.Textarea,
    )

    app_id = ChoiceField(
        label=ugettext_lazy("Application"),
        required=True,
    )

    action = CharField(
        initial='invite',
        widget=forms.HiddenInput(),
    )

    registration_message_type = ChoiceField(
        required=True,
        choices=DEFAULT_CUSTOM_CHOICES,
    )

    custom_registration_message = TrimmedCharField(
        label=ugettext_lazy("Registration Message"),
        required=False,
        widget=forms.Textarea,
    )

    phone_type = ChoiceField(
        label=ugettext_lazy("Recipient phones are"),
        required=True,
        choices=PHONE_CHOICES,
    )

    make_email_required = ChoiceField(
        label=ugettext_lazy("Make email required at registration"),
        required=True,
        choices=ENABLED_DISABLED_CHOICES,
    )

    @property
    def android_only(self):
        return self.cleaned_data.get(
            'phone_type') == self.PHONE_TYPE_ANDROID_ONLY

    @property
    def require_email(self):
        return self.cleaned_data.get('make_email_required') == ENABLED

    def set_app_id_choices(self):
        app_ids = get_built_app_ids(self.domain)
        choices = []
        for app_doc in iter_docs(Application.get_db(), app_ids):
            # This will return both Application and RemoteApp docs, but
            # they both have a name attribute
            choices.append((app_doc['_id'], app_doc['name']))
        choices.sort(key=lambda x: x[1])
        self.fields['app_id'].choices = choices

    def __init__(self, *args, **kwargs):
        if 'domain' not in kwargs:
            raise Exception('Expected kwargs: domain')
        self.domain = kwargs.pop('domain')

        super(SendRegistrationInvitationsForm, self).__init__(*args, **kwargs)
        self.set_app_id_choices()

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = 'col-sm-4'
        self.helper.field_class = 'col-sm-8'
        self.helper.layout = crispy.Layout(
            crispy.Div(
                'app_id',
                crispy.Field(
                    'phone_numbers',
                    placeholder=_("Enter phone number(s) in international "
                                  "format. Example: +27..., +91...,"),
                ),
                'phone_type',
                InlineField('action'),
                css_class='modal-body',
            ),
            hqcrispy.FieldsetAccordionGroup(
                _("Advanced"),
                crispy.Field(
                    'registration_message_type',
                    data_bind='value: registration_message_type',
                ),
                crispy.Div(
                    crispy.Field(
                        'custom_registration_message',
                        placeholder=_("Enter registration SMS"),
                    ),
                    data_bind='visible: showCustomRegistrationMessage',
                ),
                'make_email_required',
                active=False),
            crispy.Div(
                twbscrispy.StrictButton(
                    _("Cancel"),
                    data_dismiss='modal',
                    css_class="btn btn-default",
                ),
                twbscrispy.StrictButton(
                    _("Send Invitation"),
                    type="submit",
                    css_class="btn btn-primary",
                ),
                css_class='modal-footer',
            ),
        )

    def clean_phone_numbers(self):
        value = self.cleaned_data.get('phone_numbers', '')
        phone_list = [strip_plus(s.strip()) for s in value.split(',')]
        phone_list = [phone for phone in phone_list if phone]
        if len(phone_list) == 0:
            raise ValidationError(_("This field is required."))
        for phone_number in phone_list:
            validate_phone_number(phone_number)
        return list(set(phone_list))

    def clean_custom_registration_message(self):
        value = self.cleaned_data.get('custom_registration_message')
        if self.cleaned_data.get('registration_message_type') == CUSTOM:
            if not value:
                raise ValidationError(_("Please enter a message"))
            return value

        return None
Exemple #37
0
class BackendMapForm(Form):
    catchall_backend_id = ChoiceField(label=ugettext_lazy("Catch-All Gateway"),
                                      required=False)
    backend_map = CharField(required=False)

    def __init__(self, *args, **kwargs):
        backends = kwargs.pop('backends')
        super(BackendMapForm, self).__init__(*args, **kwargs)
        self.set_catchall_choices(backends)
        self.setup_crispy()

    def set_catchall_choices(self, backends):
        backend_choices = [('', _("(none)"))]
        backend_choices.extend([(backend.pk, backend.name)
                                for backend in backends])
        self.fields['catchall_backend_id'].choices = backend_choices

    def setup_crispy(self):
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-2 col-md-2'
        self.helper.field_class = 'col-sm-5 col-md-5'
        self.helper.form_method = 'POST'
        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Default Gateways"),
                hqcrispy.B3MultiField(
                    _("Default Gateway by Prefix"),
                    ErrorsOnlyField('backend_map'),
                    crispy.Div(data_bind="template: {"
                               " name: 'ko-template-backend-map', "
                               " data: $data"
                               "}"),
                ),
                'catchall_backend_id',
            ),
            hqcrispy.FormActions(
                StrictButton(_("Save"), type="submit",
                             css_class='btn-primary'), ),
        )

    def _clean_prefix(self, prefix):
        try:
            prefix = int(prefix)
            if prefix <= 0:
                raise ValueError()
        except (ValueError, TypeError):
            raise ValidationError(
                _("Please enter a positive number for the prefix."))

        return str(prefix)

    def _clean_backend_id(self, backend_id):
        try:
            backend_id = int(backend_id)
        except (ValueError, TypeError):
            raise ValidationError(_("Invalid Backend Specified."))

        try:
            backend = SQLMobileBackend.load(backend_id)
        except:
            raise ValidationError(_("Invalid Backend Specified."))

        if (backend.deleted or not backend.is_global
                or backend.backend_type != SQLMobileBackend.SMS):
            raise ValidationError(_("Invalid Backend Specified."))

        return backend_id

    def clean_backend_map(self):
        value = self.cleaned_data.get('backend_map')
        try:
            value = json.loads(value)
        except:
            raise ValidationError(
                _("An unexpected error occurred. Please reload and try again"))

        cleaned_value = {}
        for mapping in value:
            prefix = self._clean_prefix(mapping.get('prefix'))
            if prefix in cleaned_value:
                raise ValidationError(
                    _("Prefix is specified twice: %s") % prefix)

            cleaned_value[prefix] = self._clean_backend_id(
                mapping.get('backend_id'))
        return cleaned_value

    def clean_catchall_backend_id(self):
        value = self.cleaned_data.get('catchall_backend_id')
        if not value:
            return None

        return self._clean_backend_id(value)
Exemple #38
0
from django.db import models
from django.utils.translation import ugettext_lazy

import datetime

from accounts.models import CompanyProfile, ConsultantProfile
from customers.models import Customer

BILLING_RATE_CHOICES = [
    ('HR', ugettext_lazy('Hourly Rate')),
    ('FD', ugettext_lazy('Flat Daily Rate')),
    ('PR', ugettext_lazy('Per-Project Basis')),
]


# Create your models here.
class Project(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    third_party_identifier = models.CharField(max_length=255, blank=True)
    start_date = models.DateField(default=datetime.date.today)
    end_date = models.DateField(blank=True, null=True)
    description = models.TextField(blank=True)
    billing_rate = models.CharField(max_length=2,
                                    default='HR',
                                    choices=BILLING_RATE_CHOICES)

    def __str__(self):
        return self.name

Exemple #39
0
def init():
    """Initialize the Networks module."""
    menu = cfg.main_menu.get('system:index')
    menu.add_urlname(ugettext_lazy('Networks'), 'glyphicon-signal',
                     'networks:index', 18)
Exemple #40
0
SHOW_ALL = "SHOW_ALL"
SHOW_INVALID = "SHOW_INVALID"
HIDE_ALL = "HIDE_ALL"

TIME_BEFORE = "BEFORE"
TIME_AFTER = "AFTER"
TIME_BETWEEN = "BETWEEN"

WELCOME_RECIPIENT_NONE = 'NONE'
WELCOME_RECIPIENT_CASE = 'CASE'
WELCOME_RECIPIENT_MOBILE_WORKER = 'MOBILE_WORKER'
WELCOME_RECIPIENT_ALL = 'ALL'

WELCOME_RECIPIENT_CHOICES = (
    (WELCOME_RECIPIENT_NONE, ugettext_lazy('Nobody')),
    (WELCOME_RECIPIENT_CASE, ugettext_lazy('Cases only')),
    (WELCOME_RECIPIENT_MOBILE_WORKER, ugettext_lazy('Mobile Workers only')),
    (WELCOME_RECIPIENT_ALL, ugettext_lazy('Cases and Mobile Workers')),
)


class ForwardingRuleForm(Form):
    forward_type = ChoiceField(choices=FORWARDING_CHOICES)
    keyword = CharField(required=False)
    backend_id = CharField()

    def __init__(self, *args, **kwargs):
        super(ForwardingRuleForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
Exemple #41
0
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# we don't want the whole list of languages
LANGUAGES = (
    ('en', ugettext_lazy('en')),
    ('de', ugettext_lazy('de')),
    ('fr', ugettext_lazy('fr')),
)
MODELTRANSLATION_LANGUAGES = ('en', 'de', 'fr')
MODELTRANSLATION_FALLBACK_LANGUAGES = {'default': ('en', ), 'fr': ('de', )}
MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'en'

LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

# static_root the absolute path to the directory where static files
# from all app are collected in one place to be served in production
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Exemple #42
0
class AdminSite:
    """
    An AdminSite object encapsulates an instance of the Django admin application, ready
    to be hooked in to your URLconf. Models are registered with the AdminSite using the
    register() method, and the get_urls() method can then be used to access Django view
    functions that present a full admin interface for the collection of registered
    models.
    """

    # Text to put at the end of each page's <title>.
    site_title = ugettext_lazy('Django site admin')

    # Text to put in each page's <h1>.
    site_header = ugettext_lazy('Django administration')

    # Text to put at the top of the admin index page.
    index_title = ugettext_lazy('Site administration')

    # URL for the "View site" link at the top of each admin page.
    site_url = '/'

    _empty_value_display = '-'

    login_form = None
    index_template = None
    app_index_template = None
    login_template = None
    logout_template = None
    password_change_template = None
    password_change_done_template = None

    def __init__(self, name='admin'):
        self._registry = {}  # model_class class -> admin_class instance
        self.name = name
        self._actions = {'delete_selected': actions.delete_selected}
        self._global_actions = self._actions.copy()
        all_sites.add(self)

    def check(self, app_configs):
        """
        Run the system checks on all ModelAdmins, except if they aren't
        customized at all.
        """
        if app_configs is None:
            app_configs = apps.get_app_configs()
        app_configs = set(app_configs)  # Speed up lookups below

        errors = []
        modeladmins = (o for o in self._registry.values()
                       if o.__class__ is not ModelAdmin)
        for modeladmin in modeladmins:
            if modeladmin.model._meta.app_config in app_configs:
                errors.extend(modeladmin.check())
        return errors

    def register(self, model_or_iterable, admin_class=None, **options):
        """
        Registers the given model(s) with the given admin class.

        The model(s) should be Model classes, not instances.

        If an admin class isn't given, it will use ModelAdmin (the default
        admin options). If keyword arguments are given -- e.g., list_display --
        they'll be applied as options to the admin class.

        If a model is already registered, this will raise AlreadyRegistered.

        If a model is abstract, this will raise ImproperlyConfigured.
        """
        if not admin_class:
            admin_class = ModelAdmin

        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model._meta.abstract:
                raise ImproperlyConfigured(
                    'The model %s is abstract, so it cannot be registered with admin.'
                    % model.__name__)

            if model in self._registry:
                raise AlreadyRegistered('The model %s is already registered' %
                                        model.__name__)

            # Ignore the registration if the model has been
            # swapped out.
            if not model._meta.swapped:
                # If we got **options then dynamically construct a subclass of
                # admin_class with those **options.
                if options:
                    # For reasons I don't quite understand, without a __module__
                    # the created class appears to "live" in the wrong place,
                    # which causes issues later on.
                    options['__module__'] = __name__
                    admin_class = type("%sAdmin" % model.__name__,
                                       (admin_class, ), options)

                # Instantiate the admin class to save in the registry
                self._registry[model] = admin_class(model, self)

    def unregister(self, model_or_iterable):
        """
        Unregisters the given model(s).

        If a model isn't already registered, this will raise NotRegistered.
        """
        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model not in self._registry:
                raise NotRegistered('The model %s is not registered' %
                                    model.__name__)
            del self._registry[model]

    def is_registered(self, model):
        """
        Check if a model class is registered with this `AdminSite`.
        """
        return model in self._registry

    def add_action(self, action, name=None):
        """
        Register an action to be available globally.
        """
        name = name or action.__name__
        self._actions[name] = action
        self._global_actions[name] = action

    def disable_action(self, name):
        """
        Disable a globally-registered action. Raises KeyError for invalid names.
        """
        del self._actions[name]

    def get_action(self, name):
        """
        Explicitly get a registered global action whether it's enabled or
        not. Raises KeyError for invalid names.
        """
        return self._global_actions[name]

    @property
    def actions(self):
        """
        Get all the enabled actions as an iterable of (name, func).
        """
        return iter(self._actions.items())

    @property
    def empty_value_display(self):
        return self._empty_value_display

    @empty_value_display.setter
    def empty_value_display(self, empty_value_display):
        self._empty_value_display = empty_value_display

    def has_permission(self, request):
        """
        Returns True if the given HttpRequest has permission to view
        *at least one* page in the admin site.
        """
        return request.user.is_active and request.user.is_staff

    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super().get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout',
                                           current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    request.get_full_path(),
                    reverse('admin:login', current_app=self.name))
            return view(request, *args, **kwargs)

        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view)

    def get_urls(self):
        from django.conf.urls import url, include
        # Since this module gets imported in the application's root package,
        # it cannot import models from other applications at the module level,
        # and django.contrib.contenttypes.views imports ContentType.
        from django.contrib.contenttypes import views as contenttype_views

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)

            wrapper.admin_site = self
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            url(r'^$', wrap(self.index), name='index'),
            url(r'^login/$', self.login, name='login'),
            url(r'^logout/$', wrap(self.logout), name='logout'),
            url(r'^password_change/$',
                wrap(self.password_change, cacheable=True),
                name='password_change'),
            url(r'^password_change/done/$',
                wrap(self.password_change_done, cacheable=True),
                name='password_change_done'),
            url(r'^jsi18n/$',
                wrap(self.i18n_javascript, cacheable=True),
                name='jsi18n'),
            url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
                wrap(contenttype_views.shortcut),
                name='view_on_site'),
        ]

        # Add in each model's views, and create a list of valid URLS for the
        # app_index
        valid_app_labels = []
        for model, model_admin in self._registry.items():
            urlpatterns += [
                url(
                    r'^%s/%s/' %
                    (model._meta.app_label, model._meta.model_name),
                    include(model_admin.urls)),
            ]
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)

        # If there were ModelAdmins registered, we should have a list of app
        # labels for which we need to allow access to the app_index view,
        if valid_app_labels:
            regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
            urlpatterns += [
                url(regex, wrap(self.app_index), name='app_list'),
            ]
        return urlpatterns

    @property
    def urls(self):
        return self.get_urls(), 'admin', self.name

    def each_context(self, request):
        """
        Returns a dictionary of variables to put in the template context for
        *every* page in the admin site.

        For sites running on a subpath, use the SCRIPT_NAME value if site_url
        hasn't been customized.
        """
        script_name = request.META['SCRIPT_NAME']
        site_url = script_name if self.site_url == '/' and script_name else self.site_url
        return {
            'site_title': self.site_title,
            'site_header': self.site_header,
            'site_url': site_url,
            'has_permission': self.has_permission(request),
            'available_apps': self.get_app_list(request),
        }

    def password_change(self, request, extra_context=None):
        """
        Handles the "change password" task -- both form display and validation.
        """
        from django.contrib.admin.forms import AdminPasswordChangeForm
        from django.contrib.auth.views import PasswordChangeView
        url = reverse('admin:password_change_done', current_app=self.name)
        defaults = {
            'form_class':
            AdminPasswordChangeForm,
            'success_url':
            url,
            'extra_context':
            dict(self.each_context(request), **(extra_context or {})),
        }
        if self.password_change_template is not None:
            defaults['template_name'] = self.password_change_template
        request.current_app = self.name
        return PasswordChangeView.as_view(**defaults)(request)

    def password_change_done(self, request, extra_context=None):
        """
        Displays the "success" page after a password change.
        """
        from django.contrib.auth.views import PasswordChangeDoneView
        defaults = {
            'extra_context':
            dict(self.each_context(request), **(extra_context or {})),
        }
        if self.password_change_done_template is not None:
            defaults['template_name'] = self.password_change_done_template
        request.current_app = self.name
        return PasswordChangeDoneView.as_view(**defaults)(request)

    def i18n_javascript(self, request, extra_context=None):
        """
        Displays the i18n JavaScript that the Django admin requires.

        `extra_context` is unused but present for consistency with the other
        admin views.
        """
        return JavaScriptCatalog.as_view(
            packages=['django.contrib.admin'])(request)

    @never_cache
    def logout(self, request, extra_context=None):
        """
        Logs out the user for the given HttpRequest.

        This should *not* assume the user is already logged in.
        """
        from django.contrib.auth.views import LogoutView
        defaults = {
            'extra_context':
            dict(
                self.each_context(request),
                # Since the user isn't logged out at this point, the value of
                # has_permission must be overridden.
                has_permission=False,
                **(extra_context or {})),
        }
        if self.logout_template is not None:
            defaults['template_name'] = self.logout_template
        request.current_app = self.name
        return LogoutView.as_view(**defaults)(request)

    @never_cache
    def login(self, request, extra_context=None):
        """
        Displays the login form for the given HttpRequest.
        """
        if request.method == 'GET' and self.has_permission(request):
            # Already logged-in, redirect to admin index
            index_path = reverse('admin:index', current_app=self.name)
            return HttpResponseRedirect(index_path)

        from django.contrib.auth.views import LoginView
        # Since this module gets imported in the application's root package,
        # it cannot import models from other applications at the module level,
        # and django.contrib.admin.forms eventually imports User.
        from django.contrib.admin.forms import AdminAuthenticationForm
        context = dict(
            self.each_context(request),
            title=_('Log in'),
            app_path=request.get_full_path(),
            username=request.user.get_username(),
        )
        if (REDIRECT_FIELD_NAME not in request.GET
                and REDIRECT_FIELD_NAME not in request.POST):
            context[REDIRECT_FIELD_NAME] = reverse('admin:index',
                                                   current_app=self.name)
        context.update(extra_context or {})

        defaults = {
            'extra_context': context,
            'authentication_form': self.login_form or AdminAuthenticationForm,
            'template_name': self.login_template or 'admin/login.html',
        }
        request.current_app = self.name
        return LoginView.as_view(**defaults)(request)

    def _build_app_dict(self, request, label=None):
        """
        Builds the app dictionary. Takes an optional label parameters to filter
        models of a specific app.
        """
        app_dict = {}

        if label:
            models = {
                m: m_a
                for m, m_a in self._registry.items()
                if m._meta.app_label == label
            }
        else:
            models = self._registry

        for model, model_admin in models.items():
            app_label = model._meta.app_label

            has_module_perms = model_admin.has_module_permission(request)
            if not has_module_perms:
                continue

            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True not in perms.values():
                continue

            info = (app_label, model._meta.model_name)
            model_dict = {
                'name': capfirst(model._meta.verbose_name_plural),
                'object_name': model._meta.object_name,
                'perms': perms,
            }
            if perms.get('change'):
                try:
                    model_dict['admin_url'] = reverse(
                        'admin:%s_%s_changelist' % info, current_app=self.name)
                except NoReverseMatch:
                    pass
            if perms.get('add'):
                try:
                    model_dict['add_url'] = reverse('admin:%s_%s_add' % info,
                                                    current_app=self.name)
                except NoReverseMatch:
                    pass

            if app_label in app_dict:
                app_dict[app_label]['models'].append(model_dict)
            else:
                app_dict[app_label] = {
                    'name':
                    apps.get_app_config(app_label).verbose_name,
                    'app_label':
                    app_label,
                    'app_url':
                    reverse(
                        'admin:app_list',
                        kwargs={'app_label': app_label},
                        current_app=self.name,
                    ),
                    'has_module_perms':
                    has_module_perms,
                    'models': [model_dict],
                }

        if label:
            return app_dict.get(label)
        return app_dict

    def get_app_list(self, request):
        """
        Returns a sorted list of all the installed apps that have been
        registered in this site.
        """
        app_dict = self._build_app_dict(request)

        # Sort the apps alphabetically.
        app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

        return app_list

    @never_cache
    def index(self, request, extra_context=None):
        """
        Displays the main admin index page, which lists all of the installed
        apps that have been registered in this site.
        """
        app_list = self.get_app_list(request)

        context = dict(
            self.each_context(request),
            title=self.index_title,
            app_list=app_list,
        )
        context.update(extra_context or {})

        request.current_app = self.name

        return TemplateResponse(request, self.index_template
                                or 'admin/index.html', context)

    def app_index(self, request, app_label, extra_context=None):
        app_dict = self._build_app_dict(request, app_label)
        if not app_dict:
            raise Http404('The requested admin page does not exist.')
        # Sort the models alphabetically within each app.
        app_dict['models'].sort(key=lambda x: x['name'])
        app_name = apps.get_app_config(app_label).verbose_name
        context = dict(
            self.each_context(request),
            title=_('%(app)s administration') % {'app': app_name},
            app_list=[app_dict],
            app_label=app_label,
        )
        context.update(extra_context or {})

        request.current_app = self.name

        return TemplateResponse(
            request, self.app_index_template
            or ['admin/%s/app_index.html' % app_label, 'admin/app_index.html'],
            context)
class XForm(BaseModel):
    CLONED_SUFFIX = '_cloned'
    MAX_ID_LENGTH = 100

    xls = models.FileField(upload_to=upload_to, null=True)
    json = models.TextField(default=u'')
    description = models.TextField(default=u'', null=True)
    xml = models.TextField()

    user = models.ForeignKey(User, related_name='xforms', null=True)
    require_auth = models.BooleanField(default=False)
    shared = models.BooleanField(default=False)
    shared_data = models.BooleanField(default=False)
    downloadable = models.BooleanField(default=True)
    allows_sms = models.BooleanField(default=False)
    encrypted = models.BooleanField(default=False)

    # the following fields are filled in automatically
    sms_id_string = models.SlugField(editable=False,
                                     verbose_name=ugettext_lazy("SMS ID"),
                                     max_length=MAX_ID_LENGTH,
                                     default='')
    id_string = models.SlugField(editable=False,
                                 verbose_name=ugettext_lazy("ID"),
                                 max_length=MAX_ID_LENGTH)
    title = models.CharField(editable=False, max_length=XFORM_TITLE_LENGTH)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    last_submission_time = models.DateTimeField(blank=True, null=True)
    has_start_time = models.BooleanField(default=False)
    uuid = models.CharField(max_length=32, default=u'', db_index=True)

    uuid_regex = re.compile(r'(<instance>.*?id="[^"]+">)(.*</instance>)(.*)',
                            re.DOTALL)
    instance_id_regex = re.compile(r'<instance>.*?id="([^"]+)".*</instance>',
                                   re.DOTALL)
    uuid_node_location = 2
    uuid_bind_location = 4
    bamboo_dataset = models.CharField(max_length=60, default=u'')
    instances_with_geopoints = models.BooleanField(default=False)
    num_of_submissions = models.IntegerField(default=0)

    tags = TaggableManager()

    has_kpi_hooks = LazyDefaultBooleanField(default=False)
    kpi_asset_uid = models.CharField(max_length=32, null=True)

    class Meta:
        app_label = 'logger'
        unique_together = (("user", "id_string"), ("user", "sms_id_string"))
        verbose_name = ugettext_lazy("XForm")
        verbose_name_plural = ugettext_lazy("XForms")
        ordering = ("id_string", )
        permissions = (
            ("view_xform", _("Can view associated data")),
            ("report_xform", _("Can make submissions to the form")),
            ("move_xform", _(u"Can move form between projects")),
            ("transfer_xform", _(u"Can transfer form ownership.")),
            ("validate_xform", _(u"Can validate submissions.")),
        )

    def file_name(self):
        return self.id_string + ".xml"

    def url(self):
        return reverse("download_xform",
                       kwargs={
                           "username": self.user.username,
                           "id_string": self.id_string
                       })

    def data_dictionary(self):
        from onadata.apps.viewer.models.data_dictionary import\
            DataDictionary
        return DataDictionary.objects.get(pk=self.pk)

    @property
    def has_instances_with_geopoints(self):
        return self.instances_with_geopoints

    @property
    def kpi_hook_service(self):
        """
        Returns kpi hook service if it exists. XForm should have only one occurrence in any case.
        :return: RestService
        """
        return self.restservices.filter(name="kpi_hook").first()

    def _set_id_string(self):
        matches = self.instance_id_regex.findall(self.xml)
        if len(matches) != 1:
            raise XLSFormError(_("There should be a single id string."))
        self.id_string = matches[0]

    def _set_title(self):
        text = re.sub(r"\s+", " ", self.xml)
        matches = title_pattern.findall(text)
        title_xml = matches[0][:XFORM_TITLE_LENGTH]

        if len(matches) != 1:
            raise XLSFormError(_("There should be a single title."), matches)

        if self.title and title_xml != self.title:
            title_xml = self.title[:XFORM_TITLE_LENGTH]
            title_xml = saxutils.escape(title_xml)
            if isinstance(self.xml, str):
                self.xml = self.xml.decode('utf-8')
            self.xml = title_pattern.sub(u"<h:title>%s</h:title>" % title_xml,
                                         self.xml)

        self.title = title_xml

    def _set_description(self):
        self.description = self.description \
            if self.description and self.description != '' else self.title

    def _set_encrypted_field(self):
        if self.json and self.json != '':
            json_dict = json.loads(self.json)
            if 'submission_url' in json_dict and 'public_key' in json_dict:
                self.encrypted = True
            else:
                self.encrypted = False

    def update(self, *args, **kwargs):
        super(XForm, self).save(*args, **kwargs)

    def save(self, *args, **kwargs):
        self._set_title()
        self._set_description()
        old_id_string = self.id_string
        self._set_id_string()
        self._set_encrypted_field()
        # check if we have an existing id_string,
        # if so, the one must match but only if xform is NOT new
        if self.pk and old_id_string and old_id_string != self.id_string:
            raise XLSFormError(
                _(u"Your updated form's id_string '%(new_id)s' must match "
                  "the existing forms' id_string '%(old_id)s'." % {
                      'new_id': self.id_string,
                      'old_id': old_id_string
                  }))

        if getattr(settings, 'STRICT', True) and \
                not re.search(r"^[\w-]+$", self.id_string):
            raise XLSFormError(
                _(u'In strict mode, the XForm ID must be a '
                  'valid slug and contain no spaces.'))

        if not self.sms_id_string:
            try:
                # try to guess the form's wanted sms_id_string
                # from it's json rep (from XLSForm)
                # otherwise, use id_string to ensure uniqueness
                self.sms_id_string = json.loads(self.json).get(
                    'sms_keyword', self.id_string)
            except:
                self.sms_id_string = self.id_string

        super(XForm, self).save(*args, **kwargs)

    def __unicode__(self):
        return getattr(self, "id_string", "")

    def submission_count(self, force_update=False):
        if self.num_of_submissions == 0 or force_update:
            count = self.instances.filter(deleted_at__isnull=True).count()
            self.num_of_submissions = count
            self.save(update_fields=['num_of_submissions'])
        return self.num_of_submissions

    submission_count.short_description = ugettext_lazy("Submission Count")

    @property
    def submission_count_for_today(self):
        current_timzone_name = timezone.get_current_timezone_name()
        current_timezone = pytz.timezone(current_timzone_name)
        today = datetime.today()
        current_date = current_timezone.localize(
            datetime(today.year, today.month, today.day))
        count = self.instances.filter(deleted_at__isnull=True,
                                      date_created=current_date).count()
        return count

    def geocoded_submission_count(self):
        """Number of geocoded submissions."""
        return self.instances.filter(deleted_at__isnull=True,
                                     geom__isnull=False).count()

    def time_of_last_submission(self):
        if self.last_submission_time is None and self.num_of_submissions > 0:
            try:
                last_submission = self.instances.\
                    filter(deleted_at__isnull=True).latest("date_created")
            except ObjectDoesNotExist:
                pass
            else:
                self.last_submission_time = last_submission.date_created
                self.save()
        return self.last_submission_time

    def time_of_last_submission_update(self):
        try:
            # we also consider deleted instances in this case
            return self.instances.latest("date_modified").date_modified
        except ObjectDoesNotExist:
            pass

    @property
    def hash(self):
        return u'%s' % md5(self.xml.encode('utf8')).hexdigest()

    @property
    def can_be_replaced(self):
        if hasattr(self.submission_count, '__call__'):
            num_submissions = self.submission_count()
        else:
            num_submissions = self.submission_count
        return num_submissions == 0

    @classmethod
    def public_forms(cls):
        return cls.objects.filter(shared=True)

    def _xls_file_io(self):
        '''
        pulls the xls file from remote storage

        this should be used sparingly
        '''
        file_path = self.xls.name
        default_storage = get_storage_class()()

        if file_path != '' and default_storage.exists(file_path):
            with default_storage.open(file_path) as ff:
                if file_path.endswith('.csv'):
                    return convert_csv_to_xls(ff.read())
                else:
                    return StringIO(ff.read())

    def to_kpi_content_schema(self):
        '''
        parses xlsform structure into json representation
        of spreadsheet structure.
        '''
        if not xls_to_dicts:
            raise ImportError('formpack module needed')
        content = xls_to_dicts(self._xls_file_io())
        # a temporary fix to the problem of list_name alias
        return json.loads(
            re.sub('list name', 'list_name', json.dumps(content, indent=4)))

    def to_xlsform(self):
        '''Generate an XLS format XLSForm copy of this form.'''
        file_path = self.xls.name
        default_storage = get_storage_class()()

        if file_path != '' and default_storage.exists(file_path):
            with default_storage.open(file_path) as xlsform_file:
                if file_path.endswith('.csv'):
                    xlsform_io = convert_csv_to_xls(xlsform_file.read())
                else:
                    xlsform_io = io.BytesIO(xlsform_file.read())
            return xlsform_io
        else:
            return None

    @property
    def settings(self):
        """
        Mimic Asset settings.
        :return: Object
        """
        # As soon as we need to add custom validation statuses in Asset settings,
        # validation in add_validation_status_to_instance
        # (kobocat/onadata/apps/api/tools.py) should still work
        default_validation_statuses = getattr(settings,
                                              "DEFAULT_VALIDATION_STATUSES",
                                              [])

        # Later purpose, default_validation_statuses could be merged with a custom validation statuses dict
        # for example:
        #   self._validation_statuses.update(default_validation_statuses)

        return {"validation_statuses": default_validation_statuses}
Exemple #44
0
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.http import require_POST
from logging import Logger

from .forms import (ConnectionTypeSelectForm, EthernetForm, PPPoEForm,
                    WifiForm)
from plinth import cfg
from plinth import network
from plinth import package

logger = Logger(__name__)

subsubmenu = [{
    'url': reverse_lazy('networks:index'),
    'text': ugettext_lazy('Network Connections')
}, {
    'url': reverse_lazy('networks:scan'),
    'text': ugettext_lazy('Nearby Wi-Fi Networks')
}, {
    'url': reverse_lazy('networks:add'),
    'text': ugettext_lazy('Add Connection')
}]


def init():
    """Initialize the Networks module."""
    menu = cfg.main_menu.get('system:index')
    menu.add_urlname(ugettext_lazy('Networks'), 'glyphicon-signal',
                     'networks:index', 18)
Exemple #45
0
class ConfigureForm(forms.Form):
    """Form to configure the Dynamic DNS client."""
    help_update_url = \
        ugettext_lazy('The Variables &lt;User&gt;, &lt;Pass&gt;, &lt;Ip&gt;, '
                      '&lt;Domain&gt; may be used within the URL. For details '
                      'see the update URL templates of the example providers.')
    help_services = \
        ugettext_lazy('Please choose an update protocol according to your '
                      'provider. If your provider does not support the GnuDIP '
                      'protocol or your provider is not listed you may use '
                      'the update URL of your provider.')
    help_server = \
        ugettext_lazy('Please do not enter a URL here (like '
                      '"https://example.com/") but only the hostname of the '
                      'GnuDIP server (like "example.com").')
    help_domain = format_lazy(ugettext_lazy(
        'The public domain name you want to use to reach your '
        '{box_name}.'),
                              box_name=ugettext_lazy(cfg.box_name))
    help_disable_ssl = \
        ugettext_lazy('Use this option if your provider uses self signed '
                      'certificates.')
    help_http_auth = \
        ugettext_lazy('If this option is selected, your username and password '
                      'will be used for HTTP basic authentication.')
    help_secret = \
        ugettext_lazy('Leave this field empty if you want to keep your '
                      'current password.')
    help_ip_url = format_lazy(ugettext_lazy(
        'Optional Value. If your {box_name} is not connected '
        'directly to the Internet (i.e. connected to a NAT '
        'router) this URL is used to determine the real '
        'IP address. The URL should simply return the IP where '
        'the client comes from (example: '
        'http://myip.datasystems24.de).'),
                              box_name=ugettext_lazy(cfg.box_name))
    help_user = \
        ugettext_lazy('The username that was used when the account was '
                      'created.')

    provider_choices = (('GnuDIP', ugettext_lazy('GnuDIP')),
                        ('noip', 'noip.com'), ('selfhost', 'selfhost.bz'),
                        ('freedns', 'freedns.afraid.org'),
                        ('other', ugettext_lazy('other update URL')))

    enabled = forms.BooleanField(label=ugettext_lazy('Enable Dynamic DNS'),
                                 required=False)

    service_type = forms.ChoiceField(label=ugettext_lazy('Service Type'),
                                     help_text=help_services,
                                     choices=provider_choices)

    dynamicdns_server = TrimmedCharField(
        label=ugettext_lazy('GnuDIP Server Address'),
        required=False,
        help_text=help_server,
        validators=[
            validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
                                      ugettext_lazy('Invalid server name'))
        ])

    dynamicdns_update_url = TrimmedCharField(label=ugettext_lazy('Update URL'),
                                             required=False,
                                             help_text=help_update_url)

    disable_SSL_cert_check = forms.BooleanField(
        label=ugettext_lazy('Accept all SSL certificates'),
        help_text=help_disable_ssl,
        required=False)

    use_http_basic_auth = forms.BooleanField(
        label=ugettext_lazy('Use HTTP basic authentication'),
        help_text=help_http_auth,
        required=False)

    dynamicdns_domain = TrimmedCharField(
        label=ugettext_lazy('Domain Name'),
        help_text=help_domain,
        required=False,
        validators=[
            validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
                                      ugettext_lazy('Invalid domain name'))
        ])

    dynamicdns_user = TrimmedCharField(label=ugettext_lazy('Username'),
                                       required=False,
                                       help_text=help_user)

    dynamicdns_secret = TrimmedCharField(label=ugettext_lazy('Password'),
                                         widget=forms.PasswordInput(),
                                         required=False,
                                         help_text=help_secret)

    showpw = forms.BooleanField(label=ugettext_lazy('Show password'),
                                required=False)

    dynamicdns_ipurl = TrimmedCharField(
        label=ugettext_lazy('URL to look up public IP'),
        required=False,
        help_text=help_ip_url,
        validators=[validators.URLValidator(schemes=['http', 'https', 'ftp'])])

    def clean(self):
        cleaned_data = super(ConfigureForm, self).clean()
        dynamicdns_secret = cleaned_data.get('dynamicdns_secret')
        dynamicdns_update_url = cleaned_data.get('dynamicdns_update_url')
        dynamicdns_user = cleaned_data.get('dynamicdns_user')
        dynamicdns_domain = cleaned_data.get('dynamicdns_domain')
        dynamicdns_server = cleaned_data.get('dynamicdns_server')
        service_type = cleaned_data.get('service_type')
        old_dynamicdns_secret = self.initial['dynamicdns_secret']

        # Clear the fields which are not in use
        if service_type == 'GnuDIP':
            dynamicdns_update_url = ''
        else:
            dynamicdns_server = ''

        if cleaned_data.get('enabled'):
            # Check if gnudip server or update URL is filled
            if not dynamicdns_update_url and not dynamicdns_server:
                raise forms.ValidationError(
                    _('Please provide an update URL or a GnuDIP server '
                      'address'))

            if dynamicdns_server and not dynamicdns_user:
                raise forms.ValidationError(
                    _('Please provide a GnuDIP username'))

            if dynamicdns_server and not dynamicdns_domain:
                raise forms.ValidationError(
                    _('Please provide a GnuDIP domain name'))

            # Check if a password was set before or a password is set now
            if dynamicdns_server and \
               not dynamicdns_secret and not old_dynamicdns_secret:
                raise forms.ValidationError(_('Please provide a password'))
Exemple #46
0
from weblate.trans.util import split_plural
from weblate.lang.models import Language
from weblate.trans.models import Project, SubProject, Dictionary, Advertisement
from weblate.trans.checks import CHECKS

register = template.Library()

SPACE_NL = u'<span class="hlspace space-nl" title="{0}"></span><br />'
SPACE_TAB = u'<span class="hlspace space-tab" title="{0}"></span>'

WHITESPACE_RE = re.compile(r'(  +| $|^ )')
NEWLINES_RE = re.compile(r'\r\n|\r|\n')
TYPE_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
# Mapping of status report flags to names
NAME_MAPPING = {
    True: ugettext_lazy('Good configuration'),
    False: ugettext_lazy('Bad configuration'),
    None: ugettext_lazy('Possible configuration')
}

FLAG_TEMPLATE = u'<i title="{0}" class="fa fa-{1}"></i>'


def fmt_whitespace(value):
    '''
    Formats whitespace so that it is more visible.
    '''
    # Highlight exta whitespace
    value = WHITESPACE_RE.sub('<span class="hlspace">\\1</span>', value)
    # Highlight tabs
    value = value.replace('\t', SPACE_TAB.format(_('Tab character')))
Exemple #47
0
    SCHEDULE_DATE_CASE_OPENED,
    SCHEDULE_GLOBAL_NEXT_VISIT_DATE,
)
from corehq.apps.app_manager.exceptions import (
    CaseXPathValidationError,
    LocationXpathValidationError,
    ScheduleError,
)
from django.utils.translation import ugettext as _, ugettext_lazy


DOT_INTERPOLATE_PATTERN = r'(\D|^)\.(\D|$)'

CASE_REFERENCE_VALIDATION_ERROR = ugettext_lazy(
    "Your form uses an expression which references a case, but cases are not available. Please go to form "
    "settings and either remove the case reference or (1) make sure that the module is set to display the "
    "module first and then form, and (2) make sure that all forms in this module update or close a case "
    "(which means registration forms must go in a different module)."
)


def dot_interpolate(string, replacement):
    """
    Replaces non-decimal dots in `string` with `replacement`
    """
    repl = '\g<1>%s\g<2>' % replacement
    return re.sub(DOT_INTERPOLATE_PATTERN, repl, string)


def interpolate_xpath(string, case_xpath=None, fixture_xpath=None, module=None, form=None):
    """
    Replace xpath shortcuts with full value.
Exemple #48
0
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.http import is_safe_url
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from lxml import etree
from six.moves.urllib.parse import urlparse
from translate.storage.placeables.lisa import parse_xliff, strelem_to_xml

from weblate.utils.data import data_dir

PLURAL_SEPARATOR = '\x1e\x1e'
LOCALE_SETUP = True

PRIORITY_CHOICES = (
    (60, ugettext_lazy('Very high')),
    (80, ugettext_lazy('High')),
    (100, ugettext_lazy('Medium')),
    (120, ugettext_lazy('Low')),
    (140, ugettext_lazy('Very low')),
)

# Initialize to sane locales for strxfrm
try:
    locale.setlocale(locale.LC_ALL, ('C', 'UTF-8'))
except locale.Error:
    try:
        locale.setlocale(locale.LC_ALL, ('en_US', 'UTF-8'))
    except locale.Error:
        LOCALE_SETUP = False
Exemple #49
0
from django import template
from django.utils.translation import ugettext_lazy

from inboxen.utils.flags import create_render_bool_template_tag
from tickets.models import Question


register = template.Library()


STATUS = {k: v for k, v in Question.STATUS_CHOICES}


STATUS_TO_TAGS = {
    Question.NEW: {
        "title": ugettext_lazy("New question"),
        "str": STATUS[Question.NEW],
        "class": "label-primary",
    },
    Question.IN_PROGRESS: {
        "title": ugettext_lazy("In progress"),
        "str": STATUS[Question.IN_PROGRESS],
        "class": "label-info",
    },
    Question.NEED_INFO: {
        "title": ugettext_lazy("Need more info from user"),
        "str": STATUS[Question.NEED_INFO],
        "class": "label-warning",
    },
    Question.RESOLVED: {
        "title": ugettext_lazy("Resolved question"),
Exemple #50
0
     'Deutsch'),  # codes have to match edX's ones (lms.envs.common.LANGUAGES)
)


class LazyChoicesSorter(object):
    def __init__(self, choices):
        self.choices = choices

    def __iter__(self):
        for choice in sorted(self.choices, key=lambda peer: peer[1]):
            yield choice


# These are the allowed subtitle languages, we have the same list on Videofront server
SUBTITLE_SUPPORTED_LANGUAGES = LazyChoicesSorter(
    (code, ugettext_lazy(lang)) for code, lang in global_settings.LANGUAGES
    if code not in ('zh-cn', 'zh-tw')
)  # We remove 2 deprecated chinese language codes which do not exist on Django 1.10 VideoFront

# EdX rely on this code to display current language to user, when not yet set in preferences
# This is probably a bug because user with an english browser, will have the english i18n
# still, when not set, the preference page will show 'fr' as default language.
# (student.views.dashboard use settings.LANGUAGE instead of request.LANGUAGE)

PIPELINE = True  # use djangopipeline aggregated css and js file (in production)
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = "/edx/var/edxapp/uploads"

STATIC_ROOT = "/edx/var/edxapp/staticfiles"
Exemple #51
0
 def options(self):
     return [('hin', ugettext_lazy('Hindi'))]
Exemple #52
0
class ConnectionForm(forms.Form):
    """Base form to create/edit a connection."""
    name = forms.CharField(label=_('Connection Name'))
    interface = forms.ChoiceField(
        label=_('Physical Interface'),
        choices=(),
        help_text=_('The network device that this connection should be bound '
                    'to.'))
    zone = forms.ChoiceField(
        label=_('Firewall Zone'),
        help_text=_('The firewall zone will control which services are \
available over this interfaces. Select Internal only for trusted networks.'),
        choices=[('external', _('External')), ('internal', _('Internal'))])
    ipv4_method = forms.ChoiceField(
        label=_('IPv4 Addressing Method'),
        help_text=format_lazy(ugettext_lazy(
            '"Automatic" method will make {box_name} acquire '
            'configuration from this network making it a client. "Shared" '
            'method will make {box_name} act as a router, configure '
            'clients on this network and share its Internet connection.'),
                              box_name=ugettext_lazy(cfg.box_name)),
        choices=[('auto', _('Automatic (DHCP)')), ('shared', _('Shared')),
                 ('manual', _('Manual')), ('disabled', _('Disabled'))])
    ipv4_address = forms.CharField(
        label=_('Address'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_netmask = forms.CharField(
        label=_('Netmask'),
        help_text=_('Optional value. If left blank, a default netmask '
                    'based on the address will be used.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_gateway = forms.CharField(
        label=_('Gateway'),
        help_text=_('Optional value.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_dns = forms.CharField(
        label=_('DNS Server'),
        help_text=_('Optional value. If this value is given and IPv4 '
                    'addressing method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv4_second_dns = forms.CharField(
        label=_('Second DNS Server'),
        help_text=_('Optional value. If this value is given and IPv4 '
                    'Addressing Method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv4_address],
        required=False)
    ipv6_method = forms.ChoiceField(
        label=_('IPv6 Addressing Method'),
        help_text=format_lazy(ugettext_lazy(
            '"Automatic" methods will make {box_name} acquire '
            'configuration from this network making it a client.'),
                              box_name=ugettext_lazy(cfg.box_name)),
        choices=[('auto', _('Automatic')), ('dhcp', _('Automatic, DHCP only')),
                 ('manual', _('Manual')), ('ignore', _('Ignore'))])
    ipv6_address = forms.CharField(
        label=_('Address'),
        validators=[validators.validate_ipv6_address],
        required=False)
    ipv6_prefix = forms.IntegerField(label=_('Prefix'),
                                     help_text=_('Value between 1 and 128.'),
                                     min_value=1,
                                     max_value=128,
                                     required=False)
    ipv6_gateway = forms.CharField(
        label=_('Gateway'),
        help_text=_('Optional value.'),
        validators=[validators.validate_ipv6_address],
        required=False)
    ipv6_dns = forms.CharField(
        label=_('DNS Server'),
        help_text=_('Optional value. If this value is given and IPv6 '
                    'addressing method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv6_address],
        required=False)
    ipv6_second_dns = forms.CharField(
        label=_('Second DNS Server'),
        help_text=_('Optional value. If this value is given and IPv6 '
                    'Addressing Method is "Automatic", the DNS Servers '
                    'provided by a DHCP server will be ignored.'),
        validators=[validators.validate_ipv6_address],
        required=False)

    @staticmethod
    def _get_interface_choices(device_type):
        """Return a list of choices for a given device type."""
        interfaces = network.get_interface_list(device_type)
        choices = [('', _('-- select --'))]
        for interface, mac in interfaces.items():
            display_string = '{interface} ({mac})'.format(interface=interface,
                                                          mac=mac)
            choices.append((interface, display_string))

        return choices

    def get_settings(self):
        """Return settings dict from cleaned data."""
        settings = {}
        settings['common'] = {
            'name': self.cleaned_data['name'],
            'interface': self.cleaned_data['interface'],
            'zone': self.cleaned_data['zone'],
        }
        settings['ipv4'] = self.get_ipv4_settings()
        settings['ipv6'] = self.get_ipv6_settings()
        return settings

    def get_ipv4_settings(self):
        """Return IPv4 dict from cleaned data."""
        ipv4 = {
            'method': self.cleaned_data['ipv4_method'],
            'address': self.cleaned_data['ipv4_address'],
            'netmask': self.cleaned_data['ipv4_netmask'],
            'gateway': self.cleaned_data['ipv4_gateway'],
            'dns': self.cleaned_data['ipv4_dns'],
            'second_dns': self.cleaned_data['ipv4_second_dns'],
        }
        return ipv4

    def get_ipv6_settings(self):
        """Return IPv6 dict from cleaned data."""
        ipv6 = {
            'method': self.cleaned_data['ipv6_method'],
            'address': self.cleaned_data['ipv6_address'],
            'prefix': self.cleaned_data['ipv6_prefix'],
            'gateway': self.cleaned_data['ipv6_gateway'],
            'dns': self.cleaned_data['ipv6_dns'],
            'second_dns': self.cleaned_data['ipv6_second_dns'],
        }
        return ipv6
Exemple #53
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import

from django.utils.translation import ugettext_lazy

MILESTONES = [1, 100, 250, 500, 1000, 2000, 5000, 7500, 10000, 15000, 20000,
              50000, 100000, 150000, 250000, 500000, 1000000, 2000000, 5000000,
              10000000, float('inf')]

# This is the list of iOS locales. Probably not complete but good enough.
# https://gist.github.com/jacobbubu/1836273
locales = {
    'af_NA': ugettext_lazy(u'Afrikaans (Namibia)'),
    'af_ZA': ugettext_lazy(u'Afrikaans (South Africa)'),
    'af': ugettext_lazy(u'Afrikaans'),
    'ak_GH': ugettext_lazy(u'Akan (Ghana)'),
    'ak': ugettext_lazy(u'Akan'),
    'sq_AL': ugettext_lazy(u'Albanian (Albania)'),
    'sq': ugettext_lazy(u'Albanian'),
    'am_ET': ugettext_lazy(u'Amharic (Ethiopia)'),
    'am': ugettext_lazy(u'Amharic'),
    'ar_DZ': ugettext_lazy(u'Arabic (Algeria)'),
    'ar_BH': ugettext_lazy(u'Arabic (Bahrain)'),
    'ar_EG': ugettext_lazy(u'Arabic (Egypt)'),
    'ar_IQ': ugettext_lazy(u'Arabic (Iraq)'),
    'ar_JO': ugettext_lazy(u'Arabic (Jordan)'),
    'ar_KW': ugettext_lazy(u'Arabic (Kuwait)'),
    'ar_LB': ugettext_lazy(u'Arabic (Lebanon)'),
    'ar_LY': ugettext_lazy(u'Arabic (Libya)'),
    'ar_MA': ugettext_lazy(u'Arabic (Morocco)'),
    'ar_OM': ugettext_lazy(u'Arabic (Oman)'),
Exemple #54
0
class DrillDownOptionFilter(BaseDrilldownOptionFilter):
    label = ugettext_lazy("Hierarchy")
    slug = "hierarchy"

    @property
    def filter_context(self):
        controls = []
        for level, label in enumerate(self.rendered_labels):
            controls.append({
                'label': label[0],
                'slug': label[1],
                'level': level,
            })

        return {
            'option_map': self.drilldown_map,
            'controls': controls,
            'selected': self.selected,
            'use_last': self.use_only_last,
            'notifications': self.final_notifications,
            'empty_text': self.drilldown_empty_text,
            'is_empty': not self.drilldown_map
        }

    @classmethod
    def get_labels(cls):
        return [('District', 'district'), ('Block', 'block'), ('AF', 'af')]

    @classmethod
    def _get_label_value(cls, request, label):
        slug = str(label[1])
        val = request.GET.getlist('%s_%s' % (cls.slug, str(label[1])))
        return {
            'slug': slug,
            'value': val,
        }

    @property
    @memoized
    def drilldown_map(self):
        def make_drilldown(hierarchy):
            hierarchy = [{
                "val":
                current[0] if isinstance(current, tuple) else current,
                "text":
                current[1] if isinstance(current, tuple) else current,
                "next":
                make_drilldown(next_level) if next_level else []
            } for current, next_level in hierarchy.items()]

            return sorted(hierarchy, key=lambda r: r['text'])

        return make_drilldown(self.get_hierarchy())

    @property
    def data_source(self):
        return HierarchySqlData

    def get_hierarchy(self):
        hierarchy = {}
        for location in self.data_source(config={
                'domain': self.domain
        }).get_data():
            district = location['district']
            block = location['block']
            user = ("%s %s" % (location['first_name']
                               or '', location['last_name'] or '')).strip()
            user_id = location['doc_id']
            if not (district and block and user):
                continue
            hierarchy[district] = hierarchy.get(district, {})
            hierarchy[district][block] = hierarchy[district].get(block, {})
            hierarchy[district][block][(user_id, user)] = None
        return hierarchy
Exemple #55
0
class DeleteView(generic.DeleteView):
    success_message = ugettext_lazy("Site '{0}' deleted.")
    page_title = ugettext_lazy("Delete site")
    confirmation_message = ugettext_lazy(
        "Are you sure you want to delete this site?")
Exemple #56
0
class ASHAMonthFilter(MonthFilter):
    label = ugettext_lazy("Last Reporting month of the quarter")
Exemple #57
0
class CreateView(generic.CreateView):
    page_title = ugettext_lazy("Add site")
    success_message = ugettext_lazy("Site '{0}' created.")
    template_name = 'wagtailsites/create.html'
Exemple #58
0
class IndexView(generic.IndexView):
    template_name = 'wagtailsites/index.html'
    page_title = ugettext_lazy("Sites")
    add_item_label = ugettext_lazy("Add a site")
    context_object_name = 'sites'
Exemple #59
0
class ProblemList(QueryStringSortMixin, TitleMixin, SolvedProblemMixin, ListView):
    model = Problem
    title = ugettext_lazy('Problems')
    context_object_name = 'problems'
    template_name = 'problem/list.html'
    paginate_by = 50
    sql_sort = frozenset(('points', 'ac_rate', 'user_count', 'code'))
    manual_sort = frozenset(('name', 'group', 'solved', 'type'))
    all_sorts = sql_sort | manual_sort
    default_desc = frozenset(('points', 'ac_rate', 'user_count'))
    default_sort = 'code'

    def get_paginator(self, queryset, per_page, orphans=0,
                      allow_empty_first_page=True, **kwargs):
        paginator = DiggPaginator(queryset, per_page, body=6, padding=2, orphans=orphans,
                                  allow_empty_first_page=allow_empty_first_page, **kwargs)
        if not self.in_contest:
            # Get the number of pages and then add in this magic.
            # noinspection PyStatementEffect
            paginator.num_pages

            queryset = queryset.add_i18n_name(self.request.LANGUAGE_CODE)
            sort_key = self.order.lstrip('-')
            if sort_key in self.sql_sort:
                queryset = queryset.order_by(self.order)
            elif sort_key == 'name':
                queryset = queryset.order_by(self.order.replace('name', 'i18n_name'))
            elif sort_key == 'group':
                queryset = queryset.order_by(self.order + '__name')
            elif sort_key == 'solved':
                if self.request.user.is_authenticated:
                    profile = self.request.user.profile
                    solved = user_completed_ids(profile)
                    attempted = user_attempted_ids(profile)

                    def _solved_sort_order(problem):
                        if problem.id in solved:
                            return 1
                        if problem.id in attempted:
                            return 0
                        return -1

                    queryset = list(queryset)
                    queryset.sort(key=_solved_sort_order, reverse=self.order.startswith('-'))
            elif sort_key == 'type':
                if self.show_types:
                    queryset = list(queryset)
                    queryset.sort(key=lambda problem: problem.types_list[0] if problem.types_list else '',
                                  reverse=self.order.startswith('-'))
            paginator.object_list = queryset
        return paginator

    @cached_property
    def profile(self):
        if not self.request.user.is_authenticated:
            return None
        return self.request.user.profile

    def get_contest_queryset(self):
        queryset = self.profile.current_contest.contest.contest_problems.select_related('problem__group') \
            .defer('problem__description').order_by('problem__code') \
            .annotate(user_count=Count('submission__participation', distinct=True)) \
            .order_by('order')
        queryset = TranslatedProblemForeignKeyQuerySet.add_problem_i18n_name.im_func(queryset, 'i18n_name',
                                                                                     self.request.LANGUAGE_CODE,
                                                                                     'problem__name')
        return [{
            'id': p['problem_id'],
            'code': p['problem__code'],
            'name': p['problem__name'],
            'i18n_name': p['i18n_name'],
            'group': {'full_name': p['problem__group__full_name']},
            'points': p['points'],
            'partial': p['partial'],
            'user_count': p['user_count'],
        } for p in queryset.values('problem_id', 'problem__code', 'problem__name', 'i18n_name',
                                   'problem__group__full_name', 'points', 'partial', 'user_count')]

    def get_normal_queryset(self):
        queryset = Problem.problems_list(self.request.user)

        if self.profile is not None and self.hide_solved:
            queryset = queryset.exclude(id__in=Submission.objects.filter(user=self.profile, points=F('problem__points'))
                                        .values_list('problem__id', flat=True))
        if self.show_types:
            queryset = queryset.prefetch_related('types')
        if self.category is not None:
            queryset = queryset.filter(group__id=self.category) 

        if self.request.user.has_perm('judge.see_private_problem'):
            if self.problem_visibility == 1:
                filter = Q(is_public=True)
            elif self.problem_visibility == 2:
                filter = Q(is_restricted=False, is_public=False)
            elif self.problem_visibility == 3 and self.request.user.has_perm('judge.see_restricted_problem'):
                filter = Q(is_restricted=True, is_public=False)
            else:
                filter = Q(is_restricted=False) | Q(is_public=True)
            
            if not self.request.user.has_perm('judge.see_restricted_problem'):
                filter |= Q(is_restricted=True)
            
            queryset = queryset.filter(filter)

        if self.selected_types:
            queryset = queryset.filter(types__in=self.selected_types)
        if 'search' in self.request.GET:
            self.search_query = query = ' '.join(self.request.GET.getlist('search')).strip()
            if query:
                if settings.ENABLE_FTS and self.full_text:
                    queryset = queryset.search(query, queryset.BOOLEAN).extra(order_by=['-relevance'])
                else:
                    queryset = queryset.filter(
                        Q(code__icontains=query) | Q(name__icontains=query) |
                        Q(translations__name__icontains=query, translations__language=self.request.LANGUAGE_CODE))
        self.prepoint_queryset = queryset
        if self.point_start is not None:
            queryset = queryset.filter(points__gte=self.point_start)
        if self.point_end is not None:
            queryset = queryset.filter(points__lte=self.point_end)
        return queryset.distinct()

    def get_queryset(self):
        if self.in_contest:
            return self.get_contest_queryset()
        else:
            return self.get_normal_queryset()

    def get_context_data(self, **kwargs):
        context = super(ProblemList, self).get_context_data(**kwargs)
        context['hide_solved'] = 0 if self.in_contest else int(self.hide_solved)
        context['show_types'] = 0 if self.in_contest else int(self.show_types)
        context['full_text'] = 0 if self.in_contest else int(self.full_text)
        context['problem_visibility'] = self.problem_visibility
        context['visibilities'] = {
                1 : 'Public',
                2 : 'Private',
                }
        if self.request.user.has_perm('judge.see_restricted_problem'):
            context['visibilities'][3] = 'Restricted'

        context['category'] = self.category
        context['categories'] = ProblemGroup.objects.all()
        if self.show_types:
            context['selected_types'] = self.selected_types
            context['problem_types'] = ProblemType.objects.all()
        context['has_fts'] = settings.ENABLE_FTS
        context['search_query'] = self.search_query
        context['completed_problem_ids'] = self.get_completed_problems()
        context['attempted_problems'] = self.get_attempted_problems()

        context.update(self.get_sort_paginate_context())
        if not self.in_contest:
            context.update(self.get_sort_context())
            context['hot_problems'] = hot_problems(timedelta(days=1), 5)
            context['point_start'], context['point_end'], context['point_values'] = self.get_noui_slider_points()
        else:
            context['hot_problems'] = None
            context['point_start'], context['point_end'], context['point_values'] = 0, 0, {}
            context['hide_contest_scoreboard'] = self.contest.hide_scoreboard
        return context

    def get_noui_slider_points(self):
        points = sorted(self.prepoint_queryset.values_list('points', flat=True).distinct())
        if not points:
            return 0, 0, {}
        if len(points) == 1:
            return points[0], points[0], {
                'min': points[0] - 1,
                'max': points[0] + 1,
            }

        start, end = points[0], points[-1]
        if self.point_start is not None:
            start = self.point_start
        if self.point_end is not None:
            end = self.point_end
        points_map = {0.0: 'min', 1.0: 'max'}
        size = len(points) - 1
        return start, end, {points_map.get(i / size, '%.2f%%' % (100 * i / size,)): j for i, j in enumerate(points)}

    def GET_with_session(self, request, key):
        if not request.GET:
            return request.session.get(key, False)
        return request.GET.get(key, None) == '1'

    def setup(self, request):
        self.hide_solved = self.GET_with_session(request, 'hide_solved')
        self.show_types = self.GET_with_session(request, 'show_types')
        self.full_text = self.GET_with_session(request, 'full_text')

        self.search_query = None
        self.category = None
        self.problem_visibility = None
        self.selected_types = []

        # This actually copies into the instance dictionary...
        self.all_sorts = set(self.all_sorts)
        if not self.show_types:
            self.all_sorts.discard('type')

        self.category = safe_int_or_none(request.GET.get('category'))
        self.problem_visibility = safe_int_or_none(request.GET.get('problem_visibility'))
        if 'type' in request.GET:
            try:
                self.selected_types = map(int, request.GET.getlist('type'))
            except ValueError:
                pass

        self.point_start = safe_float_or_none(request.GET.get('point_start'))
        self.point_end = safe_float_or_none(request.GET.get('point_end'))

    def get(self, request, *args, **kwargs):
        self.setup(request)

        try:
            return super(ProblemList, self).get(request, *args, **kwargs)
        except ProgrammingError as e:
            return generic_message(request, 'FTS syntax error', e.args[1], status=400)

    def post(self, request, *args, **kwargs):
        to_update = ('hide_solved', 'show_types', 'full_text')
        for key in to_update:
            if key in request.GET:
                val = request.GET.get(key) == '1'
                request.session[key] = val
            else:
                request.session.pop(key, None)
        return HttpResponseRedirect(request.get_full_path())
Exemple #60
0
class EditView(generic.EditView):
    success_message = ugettext_lazy("Site '{0}' updated.")
    error_message = ugettext_lazy("The site could not be saved due to errors.")
    delete_item_label = ugettext_lazy("Delete site")
    context_object_name = 'site'
    template_name = 'wagtailsites/edit.html'