def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return value.time

        # Attempt to parse a datetime:
        value = smart_str(value)
        # split usecs, because they are not recognized by strptime.
        if "." in value:
            try:
                value, usecs = value.split(".")
                usecs = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(_("Enter a valid time in HH:MM[:ss[.uuuuuu]] format."))
        else:
            usecs = 0
        kwargs = {"microsecond": usecs}

        try:  # Seconds are optional, so try converting seconds first.
            return datetime.time(*time.strptime(value, "%H:%M:%S")[3:6], **kwargs)
        except ValueError:
            try:  # Try without seconds.
                return datetime.time(*time.strptime(value, "%H:%M")[3:5], **kwargs)
            except ValueError:
                raise exceptions.ValidationError(_("Enter a valid time in HH:MM[:ss[.uuuuuu]] format."))
Example #2
1
    def _raise_if_cant_link_to_parent(self, parent, variables):
        """
        Validates relation possibility for `self.link_to_parent()`

        :param parent: parent product of self
        :type parent: Product
        :param variables:
        :type variables: dict|None
        """
        if parent.is_variation_child():
            raise ImpossibleProductModeException(
                _("Multilevel parentage hierarchies aren't supported (parent is a child already)"), code="multilevel"
            )
        if parent.mode == ProductMode.VARIABLE_VARIATION_PARENT and not variables:
            raise ImpossibleProductModeException(
                _("Parent is a variable variation parent, yet variables were not passed"), code="no_variables"
            )
        if parent.mode == ProductMode.SIMPLE_VARIATION_PARENT and variables:
            raise ImpossibleProductModeException(
                "Parent is a simple variation parent, yet variables were passed", code="extra_variables"
            )
        if self.mode == ProductMode.SIMPLE_VARIATION_PARENT:
            raise ImpossibleProductModeException(
                _("Multilevel parentage hierarchies aren't supported (this product is a simple variation parent)"),
                code="multilevel",
            )
        if self.mode == ProductMode.VARIABLE_VARIATION_PARENT:
            raise ImpossibleProductModeException(
                _("Multilevel parentage hierarchies aren't supported (this product is a variable variation parent)"),
                code="multilevel",
            )
Example #3
1
    def get_context_data(self, **kwargs):
        context = super(ManageResourceTypes, self).get_context_data(**kwargs)

        selected_type_names = [selected_type["name"] for selected_type in context["form"].initial["resource_types"]]

        try:
            # Set the basic types that aren't already associated
            result = [
                unselected_type
                for unselected_type in glance.metadefs_resource_types_list(self.request)
                if unselected_type["name"] not in selected_type_names
            ]
        except Exception:
            result = []
            msg = _("Error getting resource type associations.")
            exceptions.handle(self.request, msg)

        # Add the resource types previously associated, includes prefix, etc
        for initial_type in context["form"].initial["resource_types"]:
            selected_type = initial_type.copy()
            selected_type["selected"] = True
            result.insert(0, selected_type)

        context["id"] = self.kwargs["id"]
        try:
            context["resource_types"] = json.dumps(result)
        except Exception:
            context["resource_types"] = "[]"
            msg = _("Error getting resource type associations.")
            exceptions.handle(self.request, msg)

        return context
Example #4
1
def simple_login(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    patient = user.get_profile()
                    messages.success(request, _("You have logged in successfully."))
                    return HttpResponseRedirect(reverse("home"))
                else:
                    messages.error(request, _("Your account is inactive so you may not log in."))
                    return render_to_response("accounts/login.html", {"form": form}, RequestContext(request))
            else:
                messages.error(request, _("Invalid username or password."))
                return render_to_response("accounts/login.html", {"form": form}, RequestContext(request))

        else:
            return render_to_response("accounts/login.html", RequestContext(request, {"form": form}))
    # this is a GET
    return render_to_response("accounts/login.html", {"form": LoginForm()}, context_instance=RequestContext(request))
Example #5
1
def edit(request, query_id):
    query = get_object_or_404(models.Query, id=query_id)

    if request.POST:
        # Get query
        query_form = forms.QueryForm(request.POST)
        # and the recommendations
        editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)

        if query_form.is_valid():
            new_query = models.Query.get(query_form["query_string"].value())

            # Save editors picks
            if save_editorspicks(query, new_query, editors_pick_formset):
                messages.success(request, _("Editor's picks for '{0}' updated.").format(new_query))
                return redirect("wagtailsearch_editorspicks_index")
            else:
                if len(editors_pick_formset.non_form_errors()):
                    messages.error(
                        request, " ".join(error for error in editors_pick_formset.non_form_errors())
                    )  # formset level error (e.g. no forms submitted)
                else:
                    messages.error(
                        request, _("Recommendations have not been saved due to errors")
                    )  # specific errors will be displayed within form fields

    else:
        query_form = forms.QueryForm(initial=dict(query_string=query.query_string))
        editors_pick_formset = forms.EditorsPickFormSet(instance=query)

    return render(
        request,
        "wagtailsearch/editorspicks/edit.html",
        {"query_form": query_form, "editors_pick_formset": editors_pick_formset, "query": query},
    )
Example #6
1
def versions(request):
    """
    Show all Versions for an Image according to ADMIN_VERSIONS.
    """

    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get("dir", ""))
    filename = get_file(query.get("dir", ""), query.get("filename", ""))
    if path is None or filename is None:
        if path is None:
            msg = _("The requested Folder does not exist.")
        else:
            msg = _("The requested File does not exist.")
        messages.add_message(request, messages.INFO, "a message")
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = u"%s" % os.path.join(MEDIA_ROOT, DIRECTORY, path)

    return render_to_response(
        "filebrowser/versions.html",
        {
            "original": path_to_url(os.path.join(DIRECTORY, path, filename)),
            "query": query,
            "title": _(u'Versions for "%s"') % filename,
            "settings_var": get_settings_var(),
            "breadcrumbs": get_breadcrumbs(query, path),
            "breadcrumbs_title": _(u'Versions for "%s"') % filename,
        },
        context_instance=Context(request),
    )
    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)

        # Attempt to parse a datetime:
        value = smart_str(value)
        # split usecs, because they are not recognized by strptime.
        if "." in value:
            try:
                value, usecs = value.split(".")
                usecs = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(_("Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format."))
        else:
            usecs = 0
        kwargs = {"microsecond": usecs}
        try:  # Seconds are optional, so try converting seconds first.
            return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6], **kwargs)

        except ValueError:
            try:  # Try without seconds.
                return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M")[:5], **kwargs)
            except ValueError:  # Try without hour/minutes/seconds.
                try:
                    return datetime.datetime(*time.strptime(value, "%Y-%m-%d")[:3], **kwargs)
                except ValueError:
                    raise exceptions.ValidationError(
                        _("Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.")
                    )
Example #8
0
    def get_queryset(self):
        queryset = self.model.objects.all()
        self.description = self.base_description

        self.form = self.form_class(self.request.GET)
        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data["status"]:
            queryset = queryset.filter(status=data["status"]).distinct()
            self.description += _(" with status matching '%s'") % data["status"]

        if data["name"]:
            # If the value is two words, then assume they are first name and
            # last name
            parts = data["name"].split()
            if len(parts) >= 2:
                queryset = queryset.filter(
                    user__first_name__istartswith=parts[0], user__last_name__istartswith=parts[1]
                ).distinct()
            else:
                queryset = queryset.filter(
                    Q(user__first_name__istartswith=parts[0]) | Q(user__last_name__istartswith=parts[-1])
                ).distinct()
            self.description += _(" with customer name matching '%s'") % data["name"]

        if data["email"]:
            queryset = queryset.filter(Q(user__email__icontains=data["email"]) | Q(email__icontains=data["email"]))
            self.description += _(" with customer email matching '%s'") % data["email"]

        return queryset
Example #9
0
    def _trash(self, path, recursive=False):
        """
    _trash(path, recursive=False)

    Move a file or directory to trash.
    Will create a timestamped directory underneath /user/<username>/.Trash.

    Trash must be enabled for this to work.
    """
        if not self.exists(path):
            raise IOError(errno.ENOENT, _("File %s not found") % path)

        if not recursive and self.isdir(path):
            raise IOError(errno.EISDIR, _("File %s is a directory") % path)

        if path.startswith(self.trash_path):
            raise IOError(errno.EPERM, _("File %s is already trashed") % path)

        # Make path (with timestamp suffix if necessary)
        base_trash_path = self.join(self._ensure_current_trash_directory(), path[1:])
        trash_path = base_trash_path
        while self.exists(trash_path):
            trash_path = base_trash_path + str(time.time())

        # Move path to trash path
        self.mkdir(self.dirname(trash_path))
        self.rename(path, trash_path)
Example #10
0
def agency_delete(request, agency_pk):
    agency = get_object_or_404(Agency, pk=agency_pk)

    try:
        Permission.objects.check_permissions(request.user, [PERMISSION_AGENCY_DELETE])
    except PermissionDenied:
        AccessEntry.objects.check_access(PERMISSION_AGENCY_DELETE, request.user, agency)

    post_action_redirect = reverse("agency_list")

    previous = request.POST.get("previous", request.GET.get("previous", request.META.get("HTTP_REFERER", "/")))
    next = request.POST.get(
        "next",
        request.GET.get(
            "next", post_action_redirect if post_action_redirect else request.META.get("HTTP_REFERER", "/")
        ),
    )

    if request.method == "POST":
        try:
            folder.delete()
            messages.success(request, _(u"Agency: %s deleted successfully.") % agency)
        except Exception, e:
            messages.error(request, _(u"Agency: %(agency)s delete error: %(error)s") % {"agency": agency, "error": e})

        return HttpResponseRedirect(next)
Example #11
0
 def check_server_disallowed(self):
     """
     Check if server domain name or IP is disallowed in settings.py.
     """
     hostname = self.netloc_parts[2].lower()
     if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
         settings.DISALLOWED_DOMAIN_LIST):
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
     try:
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
             locals()))
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
         return
     server = long_ip(ip)
     # print 'server', server, dotted_ip(server), ip
     for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
         disallowed = disallowed.strip()
         if disallowed == '' or disallowed.startswith('#'):
             continue
         mask = bit_mask(32)
         if '/' in disallowed:
             disallowed, bits = disallowed.split('/', 1)
             mask = slash_mask(int(bits))
         identifier = long_ip(disallowed) & mask
         masked = server & mask
         if masked == identifier:
             raise ValidationError(unicode(
                 _("Server IP address %(ip)s is disallowed.") % locals()))
Example #12
0
    def process_csv_file(self):
        try:
            data = csvimport.get_rows_from_file(self.request.FILES["file"])
        except csv.Error as e:  # TODO: narrow down
            logger.error("Import failed: " + str(e))
            messages.error(
                self.request,
                _("I'm sorry, but we were unable to import this CSV file. Please " "contact support for help."),
            )
            return self.redirect_back()

        if len(data) == 0:
            messages.error(
                self.request, _("I'm sorry, but we detected this file as empty. Please " "contact support for help.")
            )

        if self.request.event.settings.get("banktransfer_csvhint") is not None:
            hint = self.request.event.settings.get("banktransfer_csvhint", as_type=dict)
            try:
                parsed = csvimport.parse(data, hint)
            except csvimport.HintMismatchError as e:  # TODO: narrow down
                logger.error("Import using stored hint failed: " + str(e))
            else:
                return self.confirm_view(parsed)

        return self.assign_view(data)
Example #13
0
    def get_detalisation(self):
        rows = []
        cart_total_price = self.cart.total_price
        discount_ = 0

        rows.append({"title": u"Сумаа заказа", "price": cart_total_price})
        if self.delivery_method:

            rows.append(
                {
                    "title": _("Delivery") + " - " + self.delivery_method.name,
                    "price": self.delivery_method.delivery_price,
                }
            )
        else:
            rows.append({"title": _("no delivery"), "price": 0})
        # if self.payment_method and self.payment_method.discount > 0:
        #    discount_ = (cart_total_price * self.payment_method.discount * -1).quantize(Decimal('.01'), rounding=ROUND_UP)
        #    rows.append({
        #        'title': _(u'Discount') + ' - '
        #                 + str((self.payment_method.discount * 100).quantize(Decimal('1.'))) + '%' ,
        #        'price': discount_,
        #    })
        #        else:
        #            rows.append({
        #                'title': _('No discounts'),
        #                'price': 0,
        #                })

        full_total = Decimal("0.0")
        for row in rows:
            full_total += row["price"]

        return {"full_total": full_total.quantize(Decimal(".01"), rounding=ROUND_DOWN), "rows": rows}
Example #14
0
        def _make_mail(locale, user, context):
            # Avoid circular import issues
            from kitsune.users.helpers import display_name

            is_asker = asker_id == user.id
            if is_asker:
                subject = _(
                    u'%s posted an answer to your question "%s"'
                    % (display_name(self.answer.creator), self.instance.title)
                )
                text_template = "questions/email/new_answer_to_asker.ltxt"
                html_template = "questions/email/new_answer_to_asker.html"
            else:
                subject = _(u"Re: %s" % self.instance.title)
                text_template = "questions/email/new_answer.ltxt"
                html_template = "questions/email/new_answer.html"

            mail = email_utils.make_mail(
                subject=subject,
                text_template=text_template,
                html_template=html_template,
                context_vars=context,
                from_email="Mozilla Support Forum " "<no-reply@support.mozilla.org>",
                to_email=user.email,
            )

            return mail
Example #15
0
def install(sender, **kwargs):
    sidebar_region, is_new = Region.objects.get_or_create(slug="sidebar")

    # Menus.
    main_menu, is_new = Menu.objects.get_or_create(slug="main", description=_("Main menu"))

    # Widgets.
    menu_widget_template, is_new = WidgetTemplate.objects.get_or_create(
        title=_("Menu"),
        slug="menu-widget-template",
        description=_("It renders a menu."),
        source="prometeo.core.widgets.base.dummy",
        template_name="menus/widgets/menu.html",
        context='{"name": ""}',
        public=False,
    )

    main_menu_widget, is_new = Widget.objects.get_or_create(
        title=_("Main menu"),
        slug="main-menu",
        template=menu_widget_template,
        context='{"name": "main"}',
        show_title=False,
        sort_order=1,
        region=sidebar_region,
    )
Example #16
0
 def clean_shipping_percentage(self):
     if self.value > 100:
         raise ValidationError(_("Percentage discount cannot be greater than 100"))
     if self.range:
         raise ValidationError(_("No range should be selected as this benefit does not " "apply to products"))
     if self.max_affected_items:
         raise ValidationError(_("Shipping discounts don't require a 'max affected items' " "attribute"))
Example #17
0
def upload(request):
    """
    Multipe File Upload.
    """

    from django.http import parse_cookie

    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get("dir", ""))
    if path is None:
        msg = _("The requested Folder does not exist.")
        messages.add_message(request, messages.INFO, "a message")
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = u"%s" % os.path.join(MEDIA_ROOT, DIRECTORY, path)

    # SESSION (used for flash-uploading)
    cookie_dict = parse_cookie(request.META.get("HTTP_COOKIE", ""))
    engine = __import__(settings.SESSION_ENGINE, {}, {}, [""])
    session_key = cookie_dict.get(settings.SESSION_COOKIE_NAME, None)

    return render_to_response(
        "filebrowser/upload.html",
        {
            "query": query,
            "title": _(u"Select files to upload"),
            "settings_var": get_settings_var(),
            "session_key": session_key,
            "breadcrumbs": get_breadcrumbs(query, path),
            "breadcrumbs_title": _(u"Upload"),
        },
        context_instance=Context(request),
    )
Example #18
0
    def restore(self, path):
        """
    restore(path)

    The root of ``path`` will be /users/<current user>/.Trash/<timestamp>.
    Removing the root from ``path`` will provide the original path.
    Ensure parent directories exist and rename path.
    """
        if not path.startswith(self.trash_path):
            raise IOError(errno.EPERM, _("File %s is not in trash") % path)

        # Build original path
        original_path = []
        split_path = self.split(path)
        while split_path[0] != self.trash_path:
            original_path.append(split_path[1])
            split_path = self.split(split_path[0])
        original_path.reverse()
        original_path = self.join(posixpath.sep, *original_path)

        # move to original path
        # the path could have been expunged.
        if self.exists(original_path):
            raise IOError(errno.EEXIST, _("Path %s already exists.") % str(smart_str(original_path)))
        self.rename(path, original_path)
Example #19
0
    def handle_noargs(self, **options):
        fs = cluster.get_hdfs()
        remote_dir = create_directories(fs)

        # Copy examples binaries
        for name in os.listdir(LOCAL_SAMPLE_DIR.get()):
            local_dir = fs.join(LOCAL_SAMPLE_DIR.get(), name)
            remote_data_dir = fs.join(remote_dir, name)
            LOG.info(
                _("Copying examples %(local_dir)s to %(remote_data_dir)s\n")
                % {"local_dir": local_dir, "remote_data_dir": remote_data_dir}
            )
            fs.do_as_user(fs.DEFAULT_USER, fs.copyFromLocal, local_dir, remote_data_dir)

        # Copy sample data
        local_dir = LOCAL_SAMPLE_DATA_DIR.get()
        remote_data_dir = fs.join(remote_dir, "data")
        LOG.info(
            _("Copying data %(local_dir)s to %(remote_data_dir)s\n")
            % {"local_dir": local_dir, "remote_data_dir": remote_data_dir}
        )
        fs.do_as_user(fs.DEFAULT_USER, fs.copyFromLocal, local_dir, remote_data_dir)

        # Load jobs
        USERNAME = "sample"
        try:
            sample_user = User.objects.get(username=USERNAME)
        except User.DoesNotExist:
            sample_user = User.objects.create(
                username=USERNAME, password="!", is_active=False, is_superuser=False, id=1100713, pk=1100713
            )
        management.call_command("loaddata", "initial_oozie_examples.json", verbosity=2)
Example #20
0
    def copyfile(self, src, dst, skip_header=False):
        sb = self._stats(src)
        if sb is None:
            raise IOError(errno.ENOENT, _("Copy src '%s' does not exist") % src)
        if sb.isDir:
            raise IOError(errno.INVAL, _("Copy src '%s' is a directory") % src)
        if self.isdir(dst):
            raise IOError(errno.INVAL, _("Copy dst '%s' is a directory") % dst)

        offset = 0

        while True:
            data = self.read(src, offset, UPLOAD_CHUNK_SIZE.get())
            if offset == 0:
                if skip_header:
                    n = data.index("\n")
                    if n > 0:
                        data = data[n + 1 :]
                self.create(
                    dst,
                    overwrite=True,
                    blocksize=sb.blockSize,
                    replication=sb.replication,
                    permission=oct(stat.S_IMODE(sb.mode)),
                    data=data,
                )

            if offset != 0:
                self.append(dst, data)

            cnt = len(data)
            if cnt < UPLOAD_CHUNK_SIZE.get():
                break

            offset += cnt
Example #21
0
    def get_queryset(self):
        queryset = self.model.objects.all().order_by("-date_joined")
        self.desc_ctx = {"main_filter": _("All users"), "email_filter": "", "name_filter": ""}

        if "email" not in self.request.GET:
            self.form = self.form_class()
            return queryset

        self.form = self.form_class(self.request.GET)

        if not self.form.is_valid():
            return queryset

        data = self.form.cleaned_data

        if data["email"]:
            email = normalise_email(data["email"])
            queryset = queryset.filter(email__startswith=email)
            self.desc_ctx["email_filter"] = _(" with email matching '%s'") % email
        if data["name"]:
            # If the value is two words, then assume they are first name and
            # last name
            parts = data["name"].split()
            if len(parts) == 2:
                condition = Q(first_name__istartswith=parts[0]) | Q(last_name__istartswith=parts[1])
            else:
                condition = Q(first_name__istartswith=data["name"]) | Q(last_name__istartswith=data["name"])
            queryset = queryset.filter(condition).distinct()
            self.desc_ctx["name_filter"] = _(" with name matching '%s'") % data["name"]

        return queryset
Example #22
0
File: views.py Project: kfairch/hue
def kill_job(request, job):
    if request.method != "POST":
        raise Exception(_("kill_job may only be invoked with a POST (got a %(method)s).") % dict(method=request.method))

    if job.user != request.user.username and not request.user.is_superuser:
        access_warn(request, _("Insufficient permission"))
        raise MessageException(
            _("Permission denied.  User %(username)s cannot delete user %(user)s's job.")
            % dict(username=request.user.username, user=job.user)
        )

    job.kill()
    cur_time = time.time()
    while time.time() - cur_time < 15:
        job = Job.from_id(jt=request.jt, jobid=job.jobId)

        if job.status not in ["RUNNING", "QUEUED"]:
            if request.REQUEST.get("next"):
                return HttpResponseRedirect(request.REQUEST.get("next"))
            elif request.REQUEST.get("format") == "json":
                return HttpResponse(encode_json_for_js({"status": 0}), mimetype="application/json")
            else:
                raise MessageException("Job Killed")
        time.sleep(1)
        job = Job.from_id(jt=request.jt, jobid=job.jobId)

    raise Exception(_("Job did not appear as killed within 15 seconds."))
Example #23
0
 def recent_activity(self, min_count=2):
     comments = self.comments.filter(deleted=False)
     today = datetime.date.today()
     day = today.day
     month = today.month
     year = today.year
     # get today's commments count
     today_comments_count = comments.filter(
         created_on__day=day, created_on__month=month, created_on__year=year
     ).count()
     if today_comments_count >= min_count:
         return today_comments_count, _("today")
     # get this week comments count
     week = today.isocalendar()[1]
     first_day = datetime.date(year, 1, 1)
     delta_days = first_day.isoweekday() - 1
     delta_weeks = week
     if year == first_day.isocalendar()[0]:
         delta_weeks -= 1
     week_start_delta = datetime.timedelta(days=-delta_days, weeks=delta_weeks)
     week_start = first_day + week_start_delta
     week_end_delta = datetime.timedelta(days=7 - delta_days, weeks=delta_weeks)
     week_end = first_day + week_end_delta
     this_week_comments_count = comments.filter(created_on__gte=week_start, created_on__lt=week_end).count()
     if this_week_comments_count >= min_count:
         return this_week_comments_count, _("this week")
     # get this month comments count
     this_month_comments_count = comments.filter(created_on__month=month, created_on__year=year).count()
     return this_month_comments_count, _("this month")
Example #24
0
 def get_context_data(self, *args, **kwargs):
     context = super(MeetingDetailView, self).get_context_data(*args, **kwargs)
     cm = context["object"]
     colors = {}
     speakers = cm.parts.order_by("speaker__mk").values_list("header", "speaker__mk").distinct()
     n = speakers.count()
     for (i, (p, mk)) in enumerate(speakers):
         (r, g, b) = colorsys.hsv_to_rgb(float(i) / n, 0.5 if mk else 0.3, 255)
         colors[p] = "rgb(%i, %i, %i)" % (r, g, b)
     context["title"] = _("%(committee)s meeting on %(date)s") % {
         "committee": cm.committee.name,
         "date": cm.date_string,
     }
     context["description"] = _("%(committee)s meeting on %(date)s on topic %(topic)s") % {
         "committee": cm.committee.name,
         "date": cm.date_string,
         "topic": cm.topics,
     }
     context["description"] = clean_string(context["description"]).replace('"', "")
     page = self.request.GET.get("page", None)
     if page:
         context["description"] += _(" page %(page)s") % {"page": page}
     context["colors"] = colors
     parts_lengths = {}
     for part in cm.parts.all():
         parts_lengths[part.id] = len(part.body)
     context["parts_lengths"] = json.dumps(parts_lengths)
     context["paginate_by"] = COMMITTEE_PROTOCOL_PAGINATE_BY
     return context
Example #25
0
def add(request):
    if request.POST:
        # Get query
        query_form = forms.QueryForm(request.POST)
        if query_form.is_valid():
            query = models.Query.get(query_form["query_string"].value())

            # Save editors picks
            editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)
            if save_editorspicks(query, query, editors_pick_formset):
                messages.success(request, _("Editor's picks for '{0}' created.").format(query))
                return redirect("wagtailsearch_editorspicks_index")
            else:
                if len(editors_pick_formset.non_form_errors()):
                    messages.error(
                        request, " ".join(error for error in editors_pick_formset.non_form_errors())
                    )  # formset level error (e.g. no forms submitted)
                else:
                    messages.error(
                        request, _("Recommendations have not been created due to errors")
                    )  # specific errors will be displayed within form fields
        else:
            editors_pick_formset = forms.EditorsPickFormSet()
    else:
        query_form = forms.QueryForm()
        editors_pick_formset = forms.EditorsPickFormSet()

    return render(
        request,
        "wagtailsearch/editorspicks/add.html",
        {"query_form": query_form, "editors_pick_formset": editors_pick_formset},
    )
Example #26
0
def index(request, slug=None):

    section = None

    if slug is None:
        meta = MetaSeo()
        meta.metatitle = _("Catalog")
        crumbs = [{"label": _("Catalog")}]
    else:
        section = Section.objects.get(slug=slug)

        if section is None:
            raise Http404('Section with slug "%s" not found' % slug)

        crumbs = [{"label": _("Catalog"), "url": reverse("midnight_catalog:catalog_list")}] + section.get_breadcrumbs()

        meta = MetaSeo(section)

    products = get_by_page(get_all(slug), request.GET.get("page"), getattr(settings, "MIDNIGHT_CATALOG_PAGE_SIZE", 20))

    return render(
        request,
        "midnight_catalog/catalog/index.html",
        {"products": products, "section": section, "meta": meta, "crumbs": crumbs},
    )
Example #27
0
 def get_show_fields(cls):
     return [
         "designation",
         ((_("begin date"), "begin_date"), (_("end date"), "end_date")),
         "period_set",
         "document_set",
     ]
Example #28
0
 def clean_multibuy(self):
     if not self.range:
         raise ValidationError(_("Multibuy benefits require a product range"))
     if self.value:
         raise ValidationError(_("Multibuy benefits don't require a value"))
     if self.max_affected_items:
         raise ValidationError(_("Multibuy benefits don't require a 'max affected items' " "attribute"))
Example #29
0
    def clean(self, *args, **kwargs):
        data = super(RestrictedFileField, self).clean(*args, **kwargs)
        file = data.file

        if self.content_types is not None:
            content_type_headers = getattr(file, "content_type", "")

            file_magic = magic.Magic(mime=True)
            file_content_type = file_magic.from_buffer(file.read(1024))
            file.seek(0)

            if not content_type_headers in self.content_types or not file_content_type in self.content_types:
                raise forms.ValidationError(_("Files of type {type} are not supported.".format(type=file_content_type)))

        if self.min_upload_size is not None:
            if file._size < self.min_upload_size:
                raise forms.ValidationError(
                    _(
                        "Files of size less than {min_size} are not allowed. Your file is {current_size}".format(
                            max_size=filesizeformat(self.min_upload_size), current_size=filesizeformat(file._size)
                        )
                    )
                )

        if self.max_upload_size is not None:
            if file._size > self.max_upload_size:
                raise forms.ValidationError(
                    _(
                        "Files of size greater than {max_size} are not allowed. Your file is {current_size}".format(
                            max_size=filesizeformat(self.max_upload_size), current_size=filesizeformat(file._size)
                        )
                    )
                )

        return data
Example #30
0
 def clean_shipping_absolute(self):
     if not self.value:
         raise ValidationError(_("A discount value is required"))
     if self.range:
         raise ValidationError(_("No range should be selected as this benefit does not " "apply to products"))
     if self.max_affected_items:
         raise ValidationError(_("Shipping discounts don't require a 'max affected items' " "attribute"))