django.utils.translation._.format

Here are the examples of the python api django.utils.translation._.format taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

173 Examples 7

Example 1

Project: mygpo Source File: device.py
@device_decorator
@login_required
def upload_opml(request, device):

    if not 'opml' in request.FILES:
        return HttpResponseRedirect(reverse('device-edit', args=[device.uid]))

    try:
        opml = request.FILES['opml'].read().decode('utf-8')
        subscriptions = simple.parse_subscription(opml, 'opml')
        simple.set_subscriptions(subscriptions, request.user, device.uid, None)

    except (ValueError, ExpatError, UnicodeDecodeError) as ex:
        msg = _('Could not upload subscriptions: {err}').format(err=str(ex))
        messages.error(request, msg)
        return HttpResponseRedirect(reverse('device-edit', args=[device.uid]))

    return HttpResponseRedirect(reverse('device', args=[device.uid]))

Example 2

Project: lino Source File: human.py
Function: parse_name
def parse_name(text):
    """Parse the given `text` and return a dict of `first_name` and
    `last_name` value.

    Extends :func:`name2kw` by raising a  ValidationError if necessary.

    """
    kw = name2kw(text, last_name_first=False)
    if len(kw) != 2:
        raise ValidationError(
            _("Cannot find first and last name in \"{0}\"").format(text))
    for k in ('last_name', 'first_name'):
        if kw[k] and not kw[k].isupper():
            kw[k] = upper1(kw[k])
    return kw

Example 3

Project: wger Source File: muscles.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        '''
        Send some additional data to the template
        '''
        context = super(MuscleUpdateView, self).get_context_data(**kwargs)
        context['form_action'] = reverse('exercise:muscle:edit', kwargs={'pk': self.object.id})
        context['title'] = _(u'Edit {0}').format(self.object.name)
        return context

Example 4

Project: django-widgy Source File: models.py
Function: str
    def __str__(self):
        try:
            label = self.fields_mapping[self.field_ident].label
        except KeyError:
            return u''
        else:
            return _('{0} to {1}').format(label, self.name)

Example 5

Project: cadasta-platform Source File: manager.py
    def get_from_username_or_email(self, identifier=None):
        users = self.filter(Q(username=identifier) | Q(email=identifier))
        users_count = len(users)

        if users_count == 1:
            return users[0]

        if users_count == 0:
            error = _(
                "User with username or email {} does not exist"
            ).format(identifier)
            raise self.model.DoesNotExist(error)
        else:
            error = _(
                "More than one user found for username or email {}"
            ).format(identifier)
            raise self.model.MultipleObjectsReturned(error)

Example 6

Project: open-synthesis Source File: views.py
Function: public_profile
@require_safe
@cache_page(PAGE_CACHE_TIMEOUT_SECONDS)
def public_profile(request, account_id):
    """Return a view of the public profile associated with account_id."""
    user = get_object_or_404(User, pk=account_id)
    context = {
        'user': user,
        'boards_created': user_boards_created(user)[:5],
        'boards_contributed': user_boards_contributed(user),
        'board_voted': user_boards_evaluated(user),
        'meta_description': _("Account profile for user {name}").format(name=user),
    }
    return render(request, 'boards/public_profile.html', context)

Example 7

Project: django-user-management Source File: notifications.py
def password_reset_email_handler(notification):
    """Password reset email handler."""
    base_subject = _('{domain} password reset').format(domain=notification.site.domain)
    subject = getattr(settings, 'DUM_PASSWORD_RESET_SUBJECT', base_subject)
    notification.email_subject = subject
    email_handler(notification, password_reset_email_context)

Example 8

Project: SmartElect Source File: models.py
Function: unicode
    @sensitive_variables()
    def __unicode__(self):
        return _("From {from_addr} to {to_addr}: {content}").format(
            from_addr=self.from_number_formatted,
            to_addr=self.to_number_formatted,
            content=self.message
        )

Example 9

Project: META-SHARE Source File: validators.py
def validate_matches_xml_char_production(value):
    """
    A validator function which raises a ValidationError if the given string
    should contain any characters that do not match the Char production from XML
    1.0 (Second Edition), cf.
    http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Char.
    """
    for invalid_char in _INVALID_XML_CHARS:
        _pos = value.find(invalid_char)
        if _pos != -1:
            _msg_params = {'char_pos': _pos + 1, 'char_code': ord(invalid_char)}
            # pylint: disable-msg=E1102
            raise ValidationError(_(u'The character at position {char_pos} '
                    u'(&#x{char_code:0>4x};) must not be used. Enter a string '
                    u'consisting of only characters that match the Char '
                    u'production from XML 1.0 (Second Edition), cf. '
                    u'http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Char.')
                .format(**_msg_params), code='invalid', params=_msg_params)

Example 10

Project: tuskar-ui-extras Source File: forms.py
    def _role_flavor_fields(self, plan):
        fields = {}
        for role in plan.role_list:
            field = django.forms.CharField(
                label=_("Flavor for {0}").format(role.name),
                initial=role.flavor(plan).name if role.flavor(plan) else '',
                required=False,
                widget=django.forms.HiddenInput(attrs={
                    'class': "boxes-flavor",
                }),
            )
            field.role = role
            fields['%s-flavor' % role.id] = field
        return fields

Example 11

Project: django-machina Source File: fields.py
def _get_markup_widget():
    dotted_path = machina_settings.MACHINA_MARKUP_WIDGET
    try:
        assert dotted_path is not None
        module, widget = dotted_path.rsplit('.', 1)
        module, widget = smart_str(module), smart_str(widget)
        widget = getattr(__import__(module, {}, {}, [widget]), widget)
        return widget
    except ImportError as e:
        raise ImproperlyConfigured(_('Could not import MACHINA_MARKUP_WIDGET {}: {}').format(
            machina_settings.MACHINA_MARKUP_WIDGET,
            e))
    except AssertionError:
        return Textarea

Example 12

Project: cadasta-platform Source File: api.py
Function: set_exception
def set_exception(exception):
    if (type(exception) is Http404):
        exception_msg = str(exception)
        try:
            model = re.search(
                'No (.+?) matches the given query.', exception_msg).group(1)
            exception = NotFound(_("{name} not found.").format(name=model))
        except AttributeError:
            pass
    return exception

Example 13

Project: modoboa Source File: dns.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        """Add extra variables."""
        context = super(DNSBLDomainDetailView, self).get_context_data(**kwargs)
        context.update({
            "title": _("DNSBL summary for {}").format(self.object.name)
        })
        return context

Example 14

Project: Geotrek-admin Source File: parsers.py
Function: apply_filter
    def apply_filter(self, dst, src, val):
        field = self.model._meta.get_field_by_name(dst)[0]
        if (isinstance(field, models.ForeignKey) or isinstance(field, models.ManyToManyField)):
            if dst not in self.natural_keys:
                raise ValueImportError(_(u"Destination field '{dst}' not in natural keys configuration").format(dst=dst))
            to = field.rel.to
            natural_key = self.natural_keys[dst]
            kwargs = self.field_options.get(dst, {})
            if isinstance(field, models.ForeignKey):
                val = self.filter_fk(src, val, to, natural_key, **kwargs)
            else:
                val = self.filter_m2m(src, val, to, natural_key, **kwargs)
        return val

Example 15

Project: shuup Source File: _edit.py
    def get_toolbar(self):
        save_form_id = self.get_save_form_id()
        object = self.get_object()
        delete_url = reverse_lazy("shuup_admin:service_provider.delete", kwargs={"pk": object.pk})
        toolbar = get_default_edit_toolbar(self, save_form_id, delete_url=delete_url)
        if self.object.pk:
            toolbar.append(URLActionButton(
                text=_("Create {service_name}").format(
                    service_name=self.object.service_model._meta.verbose_name),
                icon="fa fa-plus",
                url="{model_url}?provider={id}".format(
                    model_url=get_model_url(self.object.service_model, "new"),
                    id=self.object.id),
                extra_css_class="btn-info"
            ))

        return toolbar

Example 16

Project: ideascube Source File: backup.py
Function: create
    @classmethod
    def create(cls, format=None):
        format = format or Backup.FORMAT
        if format not in Backup.SUPPORTED_FORMATS_AT_CREATION:
            raise ValueError(
                _("Format {} is not supported at creation").format(format)
            )
        name = make_name(format)
        backup = Backup(name)
        backup.save()
        return backup

Example 17

Project: wger Source File: exercises.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        context = super(ExerciseUpdateView, self).get_context_data(**kwargs)
        context['form_action'] = reverse('exercise:exercise:edit', kwargs={'pk': self.object.id})
        context['title'] = _(u'Edit {0}').format(self.object.name)

        return context

Example 18

Project: wagtail-embedvideos Source File: embed_videos.py
def delete(request, embed_video_id):
    embed_video = get_object_or_404(get_embed_video_model(), id=embed_video_id)

    if not embed_video.is_editable_by_user(request.user):
        raise PermissionDenied

    if request.POST:
        embed_video.delete()
        messages.success(request, _("Video '{0}' deleted.").format(embed_video.title))
        return redirect('wagtail_embed_videos_index')

    return render(request, "wagtail_embed_videos/embed_videos/confirm_delete.html", {
        'embed_video': embed_video,
    })

Example 19

Project: wagtailplus Source File: crud.py
    def form_invalid(self, form):
        """
        Processes an invalid form submittal.

        :param form: the form instance.
        :rtype: django.http.HttpResponse.
        """
        meta = getattr(self.model, '_meta')

        #noinspection PyUnresolvedReferences
        messages.error(
            self.request,
            _(u'The {0} could not be saved due to errors.').format(
                meta.verbose_name.lower()
            )
        )

        return super(BaseEditView, self).form_invalid(form)

Example 20

Project: bibos_admin Source File: models.py
Function: resolve
    def resolve(self):
        if self.failed:
            self.status = Job.RESOLVED
            self.save()
        else:
            raise Exception(_('Cannot change status from {0} to {1}').format(
                self.status,
                Job.RESOLVED
            ))

Example 21

Project: zulip Source File: codeship.py
@api_key_only_webhook_view('Codeship')
@has_request_variables
def api_codeship_webhook(request, user_profile, client, payload=REQ(argument_type='body'),
                         stream=REQ(default='codeship')):
    # type: (HttpRequest, UserProfile, Client, Dict[str, Any], str) -> HttpResponse
    try:
        payload = payload['build']
        subject = get_subject_for_http_request(payload)
        body = get_body_for_http_request(payload)
    except KeyError as e:
        return json_error(_("Missing key {} in JSON").format(str(e)))

    check_send_message(user_profile, client, 'stream', [stream], subject, body)
    return json_success()

Example 22

Project: zulip Source File: updown.py
def send_message_for_event(event, user_profile, client, stream):
    # type: (Dict[str, Any], UserProfile, Client, str) -> None
    try:
        event_type = get_event_type(event)
        subject = SUBJECT_TEMPLATE.format(service_url=event['check']['url'])
        body = EVENT_TYPE_BODY_MAPPER[event_type](event)
    except KeyError as e:
        return json_error(_("Missing key {} in JSON").format(str(e)))
    check_send_message(user_profile, client, 'stream', [stream], subject, body)

Example 23

Project: folivora Source File: views.py
Function: post
    def post(self, request, *args, **kwargs):
        ctx = self.get_context_data(**kwargs)
        dep_form = ctx['dep_form']
        member_form = ctx['member_form']
        original_data = ProjectDependency.objects.in_bulk(
            dep_form.get_queryset())
        if all([dep_form.is_valid(), member_form.is_valid()]):
            member_form.save()
            dep_form.save()
            ProjectDependency.process_formset(dep_form,
                original_data, self.request.user)
            messages.success(request, _(u'Updated Project “{name}” '
                'successfully.').format(name=dep_form.instance.name))
            return HttpResponseRedirect(reverse('folivora_project_update',
                                    kwargs={'slug': dep_form.instance.slug}))
        return self.render_to_response(ctx)

Example 24

Project: cadasta-platform Source File: test_validators.py
    def test_validate_invalid_format(self):
        schema = {
            "$schema": "http://json-schema.org/schema#",
            "type": "object",
            "properties": {
                "email": {"type": "string", "format": "email"},
            },
        }

        with pytest.raises(JsonValidationError) as exc:
            validate_json({'email': 'blah'}, schema)

        assert (exc.value.errors['email'] ==
                _("'{value}' is not a '{type}'").format(value='blah',
                                                        type='email'))

Example 25

Project: froide Source File: forms.py
Function: init
    def __init__(self, *args, **kwargs):
        super(NewUserBaseForm, self).__init__(*args, **kwargs)
        if ALLOW_PSEUDONYM:
            self.fields["last_name"].help_text = mark_safe(
                    _('<a target="_blank" href="{url}">You may use a pseudonym if you don\'t need to receive postal messages</a>.')
                    .format(url=reverse("help-privacy") + '#pseudonym'))

Example 26

Project: djangocms-style Source File: models.py
Function: clean
    def clean(self):
        # validate for correct class name settings
        if self.additional_classes:
            additional_classes = list(
                html_class.strip() for html_class in self.additional_classes.split(',')
            )
            for class_name in additional_classes:
                class_name = class_name.strip()
                if not CLASS_NAME_FORMAT.match(class_name):
                    raise ValidationError(
                        _('"{name}" is not a proper CSS class name.').format(name=class_name)
                    )
            self.additional_classes = ', '.join(set(additional_classes))
        # validate for correct tag type settings
        if self.tag_type:
            if not TAG_TYPE_FORMAT.match(self.tag_type):
                raise ValidationError(
                    _('"{name}" is not a proper HTML tag.').format(name=self.tag_type)
                )

Example 27

Project: django-sellmo Source File: forms.py
Function: get_attribute_formfield
    def get_attribute_formfield(self, attribute):
        typ = attribute.get_type()
        choices = typ.get_choices(attribute)
        if choices is not None:
            # Always allow blank
            choices = [(typ.get_empty_value(), '---------')] + choices

        if attribute.variates:
            label = _("{attribute} (variates)").format(
                attribute=attribute.name
            )
        else:
            label = attribute.name
        field_cls, args, kwargs = typ.get_formfield(
            label=label,
            required=attribute.required,
            choices=choices
        )
        return field_cls(*args, **kwargs)

Example 28

Project: taiga-back Source File: api.py
    def create(self, *args, **kwargs):
        key = self.request.DATA.get("key", None)
        if (key and self.request.user.is_authenticated() and
                self.request.user.storage_entries.filter(key=key).exists()):
            raise exc.BadRequest(
                _("Duplicate key value violates unique constraint. "
                  "Key '{}' already exists.").format(key)
            )
        return super().create(*args, **kwargs)

Example 29

Project: akvo-rsr Source File: internal_organisation_id.py
Function: unicode
    def __unicode__(self):
        return _(u"{rec_org_name}'s internal ID for {ref_org_name}: {identifier}").format(
            rec_org_name=self.recording_org.name,
            ref_org_name=self.referenced_org.name,
            identifier=self.identifier,
        )

Example 30

Project: SchoolIdolAPI Source File: serializers.py
    def get_japanese_center_skill_details(self, obj):
        if not obj.center_skill:
            return None
        sentence, data = obj.get_center_skill_details()
        if sentence and data:
            old_lang = translation.get_language()
            translation.activate("ja")
            sentence = _(sentence).format(*[_(d) for d in data])
            translation.activate(old_lang)
            return sentence
        return None

Example 31

Project: django-widgy Source File: views.py
Function: form_valid
    def form_valid(self, form):
        page = form.instance
        unset_pks(page)
        page.root_node = page.root_node.clone(new_page=True)
        page.status = CONTENT_STATUS_DRAFT
        form.save()

        messages.success(
            self.request,
            _("'{old_title}' successfully cloned as '{new_title}'.").format(
                old_title=self.original_title,
                new_title=page.title,
            )
        )
        # We can't do a normal HTTP redirect because the form is in a modal
        # window.
        return render(self.request, 'widgy/widgy_mezzanine/clone_success.html', {
            'success_url': self.get_success_url(),
        })

Example 32

Project: open-synthesis Source File: context_processors.py
def meta(request):
    """Return a template context with site's social account information."""
    site_name = get_current_site(request)
    return {
        'twitter_account': getattr(settings, 'TWITTER_ACCOUNT', None),
        'facebook_account': getattr(settings, 'FACEBOOK_ACCOUNT', None),
        'default_description': _('{name} is an open platform for CIA-style intelligence analysis').format(name=site_name),  # nopep8
        'default_keywords': [
            _('Analysis of Competing Hypotheses'),
            _('ACH'),
            _('intelligence analysis'),
            _('current events')
        ]
    }

Example 33

Project: Geotrek-admin Source File: parsers.py
    def get_eid_kwargs(self, row):
        try:
            eid_src = self.fields[self.eid]
        except KeyError:
            raise GlobalImportError(_(u"Eid field '{eid_dst}' missing in parser configuration").format(eid_dst=self.eid))
        eid_src = self.normalize_field_name(eid_src)
        try:
            eid_val = self.get_val(row, self.eid, eid_src)
        except KeyError:
            raise GlobalImportError(_(u"Missing id field '{eid_src}'").format(eid_src=eid_src))
        if hasattr(self, 'filter_{0}'.format(self.eid)):
            eid_val = getattr(self, 'filter_{0}'.format(self.eid))(eid_src, eid_val)
        self.eid_src = eid_src
        self.eid_val = eid_val
        return {self.eid: eid_val}

Example 34

Project: django-shop Source File: taxes.py
    def add_extra_cart_row(self, cart, request):
        """
        Add a field on cart.extra_price_fields:
        """
        amount = cart.subtotal * self.taxes
        instance = {
            'label': _("{}% VAT incl.").format(settings.VALUE_ADDED_TAX),
            'amount': amount,
        }
        cart.extra_rows[self.identifier] = ExtraCartRow(instance)

Example 35

Project: mygpo Source File: time.py
Function: format_duration
@register.filter
def format_duration(sec):
    hours = sec / 60 / 60
    minutes = (sec / 60) % 60
    seconds = sec % 60
    return mark_safe(_('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds))

Example 36

Project: django-notify-x Source File: models.py
    def __str__(self):
        ctx = {
            'actor': self.actor or self.actor_text,
            'verb': self.verb,
            'description': self.description,
            'target': self.target or self.target_text,
            'obj': self.obj or self.obj_text,
            'at': timesince(self.created),
        }

        if ctx['actor']:
            if not ctx['target']:
                return _("{actor} {verb} {at} ago").format(**ctx)
            elif not ctx['obj']:
                return _("{actor} {verb} on {target} {at} ago").format(**ctx)
            elif ctx['obj']:
                return _(
                    "{actor} {verb} {obj} on {target} {at} ago").format(**ctx)
        return _("{description} -- {at} ago").format(**ctx)

Example 37

Project: ideascube Source File: views.py
def welcome_staff(request):
    """Allow to create a staff user if None exists yet."""
    if user_model.objects.filter(is_staff=True).exists():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = CreateStaffForm(request.POST)
        if form.is_valid():
            user = form.save()
            user = authenticate(serial=user.serial,
                                password=request.POST['password'])
            login(request, user)
            msg = _(u'Welcome to {}, {}!').format(
                get_config('server', 'site-name'), user)
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect('/')
    else:
        form = CreateStaffForm()
    return render(request, 'ideascube/welcome_staff.html', {'form': form})

Example 38

Project: SmartElect Source File: utils.py
def ensure_unique(model, instance, fieldname, **kwargs):
    # Ensure there are no other instances with the same value of
    # fieldname among undeleted records of this model
    #
    # :param kwargs: additional query params when checking for dupes
    if not instance.deleted:
        query_parms = {
            'deleted': False,
            fieldname: getattr(instance, fieldname),
        }
        query_parms.update(**kwargs)
        others = model.objects.filter(**query_parms)
        if instance.pk:
            others = others.exclude(pk=instance.pk)
        if others.exists():
            verbose_name = model._meta.get_field(fieldname).verbose_name
            msg = _("Duplicate value for {fieldname}").format(fieldname=verbose_name)
            raise ValidationError(msg)

Example 39

Project: django-user-management Source File: notifications.py
def validation_email_handler(notification):
    """Validation email handler."""
    base_subject = _('{domain} account validate').format(domain=notification.site.domain)
    subject = getattr(settings, 'DUM_VALIDATE_EMAIL_SUBJECT', base_subject)
    notification.email_subject = subject
    email_handler(notification, validation_email_context)

Example 40

Project: wger Source File: exercises.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        '''
        Send some additional data to the template
        '''
        context = super(ExerciseDeleteView, self).get_context_data(**kwargs)
        context['title'] = _(u'Delete {0}?').format(self.object.name)
        context['form_action'] = reverse('exercise:exercise:delete',
                                         kwargs={'pk': self.kwargs['pk']})

        return context

Example 41

Project: djangocms-cascade Source File: container.py
Function: get_identifier
    @classmethod
    def get_identifier(cls, obj):
        identifier = super(BootstrapContainerPlugin, cls).get_identifier(obj)
        breakpoints = obj.glossary.get('breakpoints')
        content = obj.glossary.get('fluid') and '(fluid) ' or ''
        if breakpoints:
            devices = ', '.join([force_text(BS3_BREAKPOINTS[bp][2]) for bp in breakpoints])
            content = _("{0}for {1}").format(content, devices)
        return format_html('{0}{1}', identifier, content)

Example 42

Project: pycontw2016 Source File: models.py
Function: str
    def __str__(self):
        return _('Review {proposal} by {reviewer}: {vote}').format(
            reviewer=self.reviewer,
            proposal=self.proposal,
            vote=self.get_vote_display(),
        )

Example 43

Project: lino Source File: models.py
Function: run_from_ui
    def run_from_ui(self, ar, **kw):

        done_for = []
        for obj in ar.selected_rows:
            obj.send_welcome_email()
            done_for.append(str(obj))

        msg = _("Welcome mail has been sent to {}.").format(
            ', '.join(done_for))
        ar.success(msg, alert=True)

Example 44

Project: zulip Source File: bitbucket2.py
@api_key_only_webhook_view('Bitbucket2')
@has_request_variables
def api_bitbucket2_webhook(request, user_profile, client, payload=REQ(argument_type='body'),
                           stream=REQ(default='bitbucket')):
    # type: (HttpRequest, UserProfile, Client, Dict[str, Any], str) -> HttpResponse
    try:
        type = get_type(request, payload)
        subject = get_subject_based_on_type(payload, type)
        body = get_body_based_on_type(type)(payload)
    except KeyError as e:
        return json_error(_("Missing key {} in JSON").format(str(e)))

    check_send_message(user_profile, client, 'stream', [stream], subject, body)
    return json_success()

Example 45

Project: SmartElect Source File: models.py
    def get_message_code_display(self):
        try:
            m = get_message(self.message_code)
        except ValueError:
            return _("Obsolete message code: {}").format(self.message_code)
        return m.label

Example 46

Project: django-allauth Source File: adapter.py
Function: clean_password
    def clean_password(self, password, user=None):
        """
        Validates a password. You can hook into this if you want to
        restric the allowed password choices.
        """
        min_length = app_settings.PASSWORD_MIN_LENGTH
        if min_length and len(password) < min_length:
            raise forms.ValidationError(_("Password must be a minimum of {0} "
                                          "characters.").format(min_length))
        validate_password(password, user)
        return password

Example 47

Project: django-shop Source File: taxes.py
    def add_extra_cart_row(self, cart, request):
        """
        Add a field on cart.extra_price_fields:
        """
        amount = cart.subtotal * self.taxes
        instance = {
            'label': _("plus {}% VAT").format(settings.VALUE_ADDED_TAX),
            'amount': amount,
        }
        cart.extra_rows[self.identifier] = ExtraCartRow(instance)
        cart.total += amount

Example 48

Project: SchoolIdolAPI Source File: serializers.py
    def get_center_skill_details(self, obj):
        if obj.center_skill:
            sentence, data = obj.get_center_skill_details()
            if sentence and data:
                return _(sentence).format(*data)
        return None

Example 49

Project: taiga-back Source File: admin.py
Function: make_public
    @transaction.atomic
    def make_public(self, request, queryset):
        total_updates = 0

        for project in queryset.exclude(is_private=False):
            project.is_private = False

            anon_permissions = list(map(lambda perm: perm[0], permissions.ANON_PERMISSIONS))
            project.anon_permissions = list(set((project.anon_permissions or []) + anon_permissions))
            project.public_permissions = list(set((project.public_permissions or []) + anon_permissions))

            project.save()
            total_updates += 1

        self.message_user(request, _("{count} successfully made public.").format(count=total_updates))

Example 50

Project: django-sellmo Source File: models.py
    def validate_unique(self, exclude=None):
        super(Variant, self).validate_unique(exclude)
        if 'slug' not in exclude:
            products = _product.models.Product.objects.filter(slug=self.slug)
            if self.pk is not None:
                # Make sure to exclude ourselves
                products = products.exclude(pk=self.pk)
            if products.count() != 0:
                model_name = _product.models.Product._meta.verbose_name
                model_name = capfirst(model_name)
                message = _(
                    "{model_name}s with this "
                    "{field_label}s already exists."
                ).format(
                    model_name=model_name,
                    field_label='slug'
                )
                raise ValidationError({'slug': [message]})
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4