def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def subtitle(self): base_subtitle = super().subtitle space = getattr(self, '_space_cache', None) if space is not None: level = getattr(space, '_level_cache', None) if level is not None: return format_lazy(_('{category}, {space}, {level}'), category=base_subtitle, space=space.title, level=level.title) return format_lazy(_('{category}, {space}'), category=base_subtitle, level=space.title) return base_subtitle
def post(self, request, *args, **kwargs): tournament = self.tournament nexisting_people = tournament.participants.filter(url_key__isnull=False).count() blank_people = tournament.participants.filter(url_key__isnull=True) nblank_people = blank_people.count() if nblank_people == 0: messages.error(self.request, _("All participants already have private URLs. " "If you want to delete them, use the Edit Database area.")) else: populate_url_keys(blank_people) generated_urls_message = ngettext( "A private URL was generated for %(nblank_people)d person.", "Private URLs were generated for all %(nblank_people)d people.", nblank_people ) % {'nblank_people': nblank_people} non_generated_urls_message = ngettext( "The already-existing private URL for %(nexisting_people)d person was left intact.", "The already-existing private URLs for %(nexisting_people)d people were left intact", nexisting_people ) % {'nexisting_people': nexisting_people} if nexisting_people == 0: messages.success(self.request, generated_urls_message) else: messages.success(self.request, format_lazy(generated_urls_message, " ", non_generated_urls_message)) return super().post(request, *args, **kwargs)
def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['last_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['names_inversed'].label = _("Names ordering") bd_field = self.fields['birth_date'] if hasattr(self, 'instance') and (self.instance.is_hosting or self.instance.is_meeting): if self.instance.is_hosting: message = _("The minimum age to be allowed hosting is {age:d}.") allowed_age = settings.HOST_MIN_AGE else: message = _("The minimum age to be allowed meeting with visitors is {age:d}.") allowed_age = settings.MEET_MIN_AGE message = format_lazy(message, age=allowed_age) bd_field.required = True bd_field.validators.append(TooNearPastValidator(settings.HOST_MIN_AGE)) bd_field.error_messages['max_value'] = message bd_field.widget.attrs['placeholder'] = 'jjjj-mm-tt' bd_field.widget.attrs['pattern'] = '[1-2][0-9]{3}-((0[1-9])|(1[0-2]))-((0[1-9])|([12][0-9])|(3[0-1]))' if hasattr(self, 'instance') and self.instance.is_in_book: message = _("This field is required to be printed in the book.") for field in self.Meta.book_required_fields: req_field = self.fields[field] req_field.required = True req_field.error_messages['required'] = message req_field.widget.attrs['data-error-required'] = message self.fields['avatar'].widget.attrs['accept'] = 'image/*'
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) config = SiteConfiguration.get_solo() self.fields['first_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['last_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['names_inversed'].label = _("Names ordering") field_bd = self.fields['birth_date'] if (hasattr(self, 'instance') and (self.instance.has_places_for_hosting or self.instance.has_places_for_meeting)): if self.instance.has_places_for_hosting: message = _("The minimum age to be allowed hosting is {age:d}.") allowed_age = config.host_min_age else: message = _("The minimum age to be allowed meeting with visitors is {age:d}.") allowed_age = config.meet_min_age message = format_lazy(message, age=allowed_age) field_bd.required = True field_bd.validators.append(TooNearPastValidator(allowed_age)) field_bd.error_messages['max_value'] = message field_bd.widget.attrs['placeholder'] = 'jjjj-mm-tt' field_bd.widget.attrs['data-date-end-date'] = '0d' field_bd.widget.attrs['pattern'] = '[1-2][0-9]{3}-((0[1-9])|(1[0-2]))-((0[1-9])|([12][0-9])|(3[0-1]))' if hasattr(self, 'instance') and self.instance.has_places_for_book: message = _("This field is required to be printed in the book.") for field in self._validation_meta.book_required_fields: req_field = self.fields[field] req_field.required = True req_field.error_messages['required'] = message req_field.widget.attrs['data-error-required'] = message self.fields['avatar'].widget.attrs['accept'] = 'image/*'
def run_from_ui(self, ar, **kw): objects = [] for obj in ar.selected_rows: objects.append(str(obj)) msg = ar.actor.disable_delete(obj, ar) if msg is not None: ar.error(None, msg, alert=True) return def ok(ar2): super(DeleteSelected, self).run_from_ui(ar, **kw) ar2.success(record_deleted=True) # hack required for extjs: if ar2.actor.detail_action: ar2.set_response( detail_handler_name=ar2.actor.detail_action.full_name()) d = dict(num=len(objects), targets=', '.join(objects)) if len(objects) == 1: d.update(type=ar.actor.model._meta.verbose_name) else: d.update(type=ar.actor.model._meta.verbose_name_plural) ar.confirm( ok, format_lazy(u"{}\n{}", _("You are about to delete %(num)d %(type)s:\n" "%(targets)s") % d, _("Are you sure ?")))
def on_analyze(cls, site): """ Add workflow actions to the models which use this workflow so that we can access them as InstanceActions. """ super(Workflow, cls).on_analyze(site) if cls.abstract: return # logger.info("20150602 Workflow.on_analyze %s", cls) used_on_models = [] for fld in cls._fields: model = getattr(fld, 'model', None) if model: used_on_models.append(model) # logger.info("20150602 %s, %s", model, cls.workflow_actions) for a in cls.workflow_actions: # if not a.action_name.startswith('wf'): if not hasattr(model, a.action_name): setattr(model, a.action_name, a) if cls.verbose_name_plural is None: if len(used_on_models) == 1: concrete_models = list(models_by_base(used_on_models[0])) if len(concrete_models) == 1: m = concrete_models[0] else: m = used_on_models[0] name = m._meta.verbose_name cls.verbose_name_plural = format_lazy(_("{} states"), name) # elif len(used_on_models) > 1: # raise Exception( # "20190103 {} is used in more than one model : {}".format( # cls, used_on_models)) else: cls.verbose_name_plural = _("States") cls.sort()
def error_msg(self, message: str, delim=None, format=None, replace=False): """ Add extra text to self.message about the reason why permission was denied. Uses lazy object so the message string is evaluated only when rendered. If optional argument `format` is given, then it's used with format_lazy to format the message with the dictionary arguments from `format` arg. Optional argument `delim` can be used to change the string used to join self.message and `message`. If optional argument `replace` is true, then self.message is replaced with the `message`. """ if delim is None: delim = ': ' if format: message = format_lazy(message, **format) if replace: self.message = message else: assert 'message' not in self.__dict__, ( "You are calling error_msg without replace=True " "after calling it with it firts. Fix your code by removing " "firts method call add replace=True to second method call too." ) self.message = string_concat(self.message, delim, message)
def __init__(self, target_state, required_roles=None, help_text=None, **kw): self.target_state = target_state assert 'required' not in kw assert 'required_roles' not in kw new_required = set(self.required_roles) if required_roles is not None: new_required |= required_roles kw.update(required_roles=new_required) if self.help_text is None: if help_text is None: # help_text = string_format( # _("Mark this as {0}"), target_state.text) # help_text = string_concat( # _("Mark this as"), ' ', target_state.text) help_text = target_state.text kw.update(help_text=help_text) super(ChangeStateAction, self).__init__(**kw) #~ logger.info('20120930 ChangeStateAction %s %s', actor,target_state) if self.label is None: self.label = target_state.text if self.button_text is None: self.button_text = target_state.button_text if self.icon_name: self.help_text = format_lazy(u"{}. {}",self.label,self.help_text)
def get_actor_label(self): if self.model is None: return self._label or self.__name__ # return self._label or \ # _("My %s") % self.model._meta.verbose_name_plural return self._label or \ format_lazy(_("My {}"), self.model._meta.verbose_name_plural)
def validate_not_all_caps(value): """Tries to figure out whether the value is all caps while it shouldn't be. Validates until 3 characters and non latin strings. """ if len(value) > 3 and value[-1:].isupper() and value == value.upper(): message = _("Today is not CapsLock day. Please try with '{correct_value}'.") raise ValidationError(format_lazy(message, correct_value=title_with_particule(value)), code="caps")
def validate_size(content): """Validates if the size of the content in not too big.""" if content.file.size > validate_size.MAX_UPLOAD_SIZE: message = format_lazy( _("Please keep filesize under {limit}. Current filesize {current}"), limit=filesizeformat(validate_size.MAX_UPLOAD_SIZE), current=filesizeformat(content.file.size)) raise ValidationError(message, code='file-size')
def subtitle(self): result = self.category.title if hasattr(self, 'locations'): return format_lazy(_('{category_title}, {num_locations}'), category_title=result, num_locations=(ungettext_lazy('%(num)d location', '%(num)d locations', 'num') % {'num': len(self.locations)})) return result
def get_locality_display(self): """ Returns "city (country)" or just "country" when no city is given. """ if self.city: return format_lazy("{city} ({state})", city=self.city, state=self.country.name) else: return self.country.name
def get_actor_label(cls): if cls._course_area is not None: courses = cls._course_area.text else: courses = rt.models.courses.Course._meta.verbose_name_plural return format_lazy( _("{enrolments} in {courses}"), enrolments=rt.models.courses.Enrolment._meta.verbose_name_plural, courses=courses)
def __get__(self, instance, cls=None): if instance is None: return self fallback_value = self.field.fallback_value if fallback_value is not None: fallback_value = format_lazy(fallback_value, model=instance._meta.verbose_name, pk=instance.pk) return lazy_get_i18n_value(getattr(instance, self.field.attname), fallback_language=self.field.fallback_language, fallback_any=self.field.fallback_any, fallback_value=fallback_value)
def get_permission_denied_message(self): try: countries = [self.country] except AttributeError: countries = set(self.user.profile.owned_places.filter( available=True, deleted=False).values_list('country', flat=True)) if not countries: return _("Only administrators can access this page") to_string = lambda item: str(Country(item).name) join_lazy = keep_lazy_text(lambda items: ", ".join(map(to_string, items))) return format_lazy(self.permission_denied_message, this_country=join_lazy(countries))
def dispatch(self, request, *args, **kwargs): code_from_kwarg = {v: k for k, v in self.book_codes.items()} code_from_kwarg.update({None: False}) self.in_book_status = code_from_kwarg[kwargs['in_book']] if self.in_book_status and not request.user.has_perm(PERM_SUPERVISOR): return HttpResponseRedirect(format_lazy( "{supervisors_url}#{section_countries}", supervisors_url=reverse_lazy('supervisors'), section_countries=pgettext_lazy("URL", "countries-list"), )) return super().dispatch(request, *args, **kwargs)
def __init__(self): self.module_name = self.__class__.__name__ if not hasattr(self, 'verbose_name'): self.verbose_name = get_verbose_name(self.module_name) if not hasattr(self, 'verbose_name_plural'): if django.VERSION < (1, 11): from django.utils.translation import string_concat self.verbose_name_plural = string_concat(self.verbose_name, 's') else: from django.utils.text import format_lazy self.verbose_name_plural = format_lazy('{}{}', self.verbose_name, 's')
def __init__(self, table_class, text=None): self.table_class = table_class model = dd.resolve_model(table_class.model) self.model = model # value = dd.full_model_name(model) value = str(table_class) if text is None: # text = model._meta.verbose_name + ' (%s)' % dd.full_model_name(model) # text = model._meta.verbose_name + ' (%s.%s)' % ( text = format_lazy(u"{} ({})",model._meta.verbose_name, value) # model.__module__, model.__name__) name = None super(VoucherType, self).__init__(value, text, name)
def request_for_response(url, post=False, data=None, files=None, stamp=None): try: last_retry = len(settings.EXERCISE_HTTP_RETRIES) - 1 n = 0 while n <= last_retry: try: request_time = time.time() if post: logger.info("POST %s", url) response = requests.post( url, data=data, files=files, timeout=settings.EXERCISE_HTTP_TIMEOUT ) else: logger.info("GET %s", url) headers = {} if stamp: headers['If-Modified-Since'] = stamp response = requests.get( url, timeout=settings.EXERCISE_HTTP_TIMEOUT, headers=headers ) request_time = time.time() - request_time logger.info("Response %d (%d sec) %s", response.status_code, request_time, url) if response.status_code == 200: return response elif response.status_code == 304: raise RemotePageNotModified(parse_expires(response)) if response.status_code < 500 or n >= last_retry: response.raise_for_status() except requests.exceptions.ConnectionError as e: logger.warning("ConnectionError %s", url); if n >= last_retry: raise e logger.info("Sleep %d sec before retry", settings.EXERCISE_HTTP_RETRIES[n]) time.sleep(settings.EXERCISE_HTTP_RETRIES[n]) n += 1 logger.error("HTTP request loop ended in unexpected state") raise RuntimeError("HTTP request loop ended in unexpected state") except requests.exceptions.RequestException as e: if e.response and e.response.status_code == 404: raise RemotePageNotFound(_("The requested resource was not found from the course service!")) raise RemotePageException(format_lazy( _("Connecting to the course service failed with {code}!"), code=e.response.status_code if e.response else '-1', ))
def __init__(self, value, name, mptext, fptext, mctext, fctext, **kw): self.mptext = mptext # male parent self.fptext = fptext self.mctext = mctext self.fctext = fctext # text = string_concat( # mptext, ' (', fptext, ') / ', mctext, ' (', fctext, ')') # text = string_concat(mctext, ' (', fctext, ')') text = format_lazy(u"{}({})",mptext, fptext) # text = "%s (%s) / %s (%s)" % (mptext, fptext, mctext, fctext) super(LinkType, self).__init__(value, text, name, **kw)
def contribute_to_class(field, cls, fieldclass, **kw): "Used by both :class:`BabelCharField` and :class:`BabelTextField` " if cls._meta.abstract: return kw.update(blank=True) for lang in settings.SITE.BABEL_LANGS: kw.update(verbose_name=format_lazy(u"{}{}", field.verbose_name, ' (' + lang.django_code + ')')) newfield = fieldclass(**kw) #~ newfield._lino_babel_field = True # used by dbtools.get_data_elems newfield._lino_babel_field = field.name newfield._babel_language = lang cls.add_to_class(six.text_type(field.name + '_' + lang.name), newfield)
def get_permission_denied_message(self, object, context_omitted=False): if not context_omitted: countries = [self.get_location(object)] if not countries[0]: countries = self.get_owner(object).owned_places.filter( deleted=False ).values_list('country', flat=True).distinct() elif not countries[0].name: countries = [] else: countries = None if not countries: return _("Only administrators can access this page") to_string = lambda item: str(Country(item).name) join_lazy = keep_lazy_text(lambda items: ", ".join(map(to_string, items))) return format_lazy(self.permission_denied_message, this_country=join_lazy(countries))
def get_meta_options(self, model): """ Returns a dictionary of fields that will be added to the Meta inner class of the historical record model. """ meta_fields = { 'ordering': ('-history_date', '-history_id'), 'get_latest_by': 'history_date', } if self.user_set_verbose_name: name = self.user_set_verbose_name else: name = format_lazy('historical {}', smart_text(model._meta.verbose_name)) meta_fields['verbose_name'] = name return meta_fields
def delete_invite(request, pk): invite = get_object_or_404(Invite, pk=pk) user_is_invitee = (request.user.email == invite.email) if not (invite.band.is_admin(request.user) or user_is_invitee or request.user.is_superuser): raise PermissionDenied invite.delete() if user_is_invitee: messages.info( request, format_lazy( _('Your invitation to join {band} has been deleted.'), band=invite.band.name if invite.band else 'Gig-O-Matic')) return redirect('member-detail', pk=request.user.id) return redirect('band-detail', pk=invite.band.id)
class AddCasesForm(UploadRawImagesForm): interface = ModelChoiceField( queryset=ComponentInterface.objects.filter( kind__in=InterfaceKind.interface_type_image()), help_text=format_lazy( ('See the <a href="{}">list of interfaces</a> for more ' "information about each interface. " "Please contact support if your desired output is missing."), reverse_lazy("algorithms:component-interface-list"), ), ) def save(self, *args, **kwargs): self._linked_task.kwargs.update( {"interface_pk": self.cleaned_data["interface"].pk}) return super().save(*args, **kwargs)
def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') self.model_variable = kwargs.pop('model_variable') self.initial_help_text = kwargs.pop('initial_help_text', '') super().__init__(*args, **kwargs) self.help_text = format_lazy( '{} {}', self.initial_help_text, _('Use Django\'s default templating language ' '(https://docs.djangoproject.com/en/%(django_version)s/ref/templates/builtins/). ' 'The {{ %(variable)s }} variable is available to the template.') % { 'django_version': mayan.__django_version__, 'variable': self.model_variable }) self.widget.attrs['model'] = self.model self.widget.attrs['data-model-variable'] = self.model_variable
def get(self, request, *args, **kwargs): try: return HttpResponseRedirect( format_lazy( "{settings_url}#{section_email}", settings_url=reverse_lazy('profile_settings', kwargs={ 'pk': request.user.profile.pk, 'slug': request.user.profile.autoslug }), section_email=pgettext_lazy("URL", "email-addr"), )) except Profile.DoesNotExist: return HttpResponseRedirect(reverse_lazy('email_update'))
def form_valid(self, form): _type = _("de l'article") if self.object.is_tutorial: _type = _("du tutoriel") elif self.object.is_opinion: _type = _("du billet") bot = get_object_or_404( User, username=settings.ZDS_APP["member"]["bot_account"]) all_authors_pk = [author.pk for author in self.object.authors.all()] for user in form.cleaned_data["users"]: if user.pk not in all_authors_pk: self.object.authors.add(user) if self.object.validation_private_message: self.object.validation_private_message.add_participant( user) all_authors_pk.append(user.pk) if user != self.request.user: url_index = reverse(self.object.type.lower() + ":find-" + self.object.type.lower(), args=[user.pk]) send_mp( bot, [user], format_lazy("{}{}", _("Ajout à la rédaction "), _type), self.versioned_object.title, render_to_string( "tutorialv2/messages/add_author_pm.md", { "content": self.object, "type": _type, "url": self.object.get_absolute_url(), "index": url_index, "user": user.username, }, ), hat=get_hat_from_settings("validation"), ) UserGallery(gallery=self.object.gallery, user=user, mode=GALLERY_WRITE).save() self.object.save() self.success_url = self.object.get_absolute_url() return super().form_valid(form)
def __new__(mcs, name, bases, dct): field_i18n = {"default": {}, "fields": {}} try: # Inherit i18n fields from superclass field_i18n = bases[0]._meta._field_i18n except IndexError: pass except AttributeError: pass for attr, field in list(dct.items()): if not isinstance(field, MultilingualField): continue # ForeignKey, OneToOneField and ManyToManyField do not have # a verbose name as first positional argument. # But those are not translatable (see above). if field.args: verbose_base = ("args", field.args[0]) else: verbose_base = ("kwargs", field.kwargs.get("verbose_name", attr)) fields = [] for lang in settings.LANGUAGES: attr_i18n = localize_attr_name(attr, lang[0]) verbose_name = format_lazy("{} ({})", verbose_base[1], lang[0].upper()) if verbose_base[0] == "args": field.args = (verbose_name, ) + field.args[1:] else: field.kwargs["verbose_name"] = verbose_name if attr_i18n in dct: raise FieldError("Explicit field {} is shadowed " "by TranslateMeta.".format(attr_i18n)) dct[attr_i18n] = field.cls(*field.args, **field.kwargs) fields.append(attr_i18n) dct[attr] = property(_i18n_attr_accessor(attr)) default = localize_attr_name(attr, settings.LANGUAGE_CODE) if default not in dct: raise ImproperlyConfigured("LANGUAGE_CODE not in LANGUAGES.") field_i18n["default"][attr] = default field_i18n["fields"][attr] = fields model = super(ModelTranslateMeta, mcs).__new__(mcs, name, bases, dct) if hasattr(model._meta, "_field_i18n"): raise FieldError("TranslateMeta map already exists!") model._meta._field_i18n = field_i18n return model
def algorithm(self): if self.choice == DISCOUNT_NOREFUND: return format_lazy('{} {}', _('No refund tariff'), self.quantities) elif self.choice == DISCOUNT_EARLY: return format_lazy( '{} {}', _('Booking, earlier than %s day(days) before arrival') % self.days, self.quantities) elif self.choice == DISCOUNT_LATER: return format_lazy( '{} {}', _('Booking, later than %s day(days) before arrival') % self.days, self.quantities) elif self.choice == DISCOUNT_PERIOD: return format_lazy('{} {}', _('Booking at least %s day(days)') % self.days, self.quantities) elif self.choice == DISCOUNT_PACKAGE: return _('Package: booking %(days)s day(days) at price of %(price_days)s day(days)') % \ dict(days=self.days, price_days=self.at_price_days) elif self.choice == DISCOUNT_HOLIDAY: return format_lazy('{} {}', _('Booking in holidays/weekend'), self.quantities) elif self.choice == DISCOUNT_SPECIAL: return format_lazy('{} {}', _('Special discount'), self.quantities) elif self.choice == DISCOUNT_LAST_MINUTE: return format_lazy( '{} {}', _('Booking after standard arrival time, over the time %(time_from)s - %(time_to)s' ) % dict(time_from=date(self.time_on, 'H:i'), time_to=date(self.time_off, 'H:i')), self.quantities) elif self.choice == DISCOUNT_CREDITCARD: return format_lazy('{} {}', _('Booking with creditcard'), self.quantities) elif self.choice == DISCOUNT_NORMAL: return format_lazy('{} {}', _('Simple discount'), self.quantities) else: return None
def add_help_text(self, kw, help_text, title, datasource, fieldname): if settings.SITE.use_quicktips: if settings.SITE.show_internal_field_names: ttt = "(%s.%s) " % (datasource, fieldname) else: ttt = '' if help_text: ttt = format_lazy(u"{}{}", ttt, help_text) if ttt: # kw.update(qtip=self.field.help_text) # kw.update(toolTipText=self.field.help_text) # kw.update(tooltip=self.field.help_text) kw.update(listeners=dict(render=js_code( "Lino.quicktip_renderer(%s,%s)" % ( py2js(title), py2js(ttt))) ))
def get_meta_options(self, model): """ Returns a dictionary of fields that will be added to the Meta inner class of the historical record model. """ meta_fields = { "ordering": ("-history_date", "-history_id"), "get_latest_by": "history_date", } if self.user_set_verbose_name: name = self.user_set_verbose_name else: name = format_lazy("historical {}", smart_text(model._meta.verbose_name)) meta_fields["verbose_name"] = name if self.app: meta_fields["app_label"] = self.app return meta_fields
class BookMetadata(MetaData): model = wf_models.Book update_fields = { 'preview_sample': { 'multiple': True, 'upload_url': format_lazy('{}{}', 'http://localhost:8000', reverse_lazy('all-model-fieldss-accept-file')), } } def get_title(self, request, view, obj: wf_models.Book): if obj: return _('Edit Book "{0}"').format(obj.printable_name) return _('Create Book')
def GenericEdit(ModelClass, request, instanceId, ModelFormClass=None, template=None, additional_context={}, pre_edit_func=None, pre_save_func=None): instance = get_object_or_404(ModelClass, pk=instanceId) if pre_edit_func: pre_edit_func(instance) ModelFormClass = ModelFormClass or GenericModelForm(ModelClass) isEdit = True title = format_lazy(u'{} {}', _('Edit'), ModelClass._meta.verbose_name) if request.method == 'POST': form = ModelFormClass(request.POST, button_mask=EDIT_BUTTONS, instance=instance) if form.is_valid(): formInstance = form.save(commit=False) if pre_save_func: pre_save_func(formInstance) formInstance.save() try: form.save_m2m() except Exception as e: pass if 'ok-submit' in request.POST: return HttpResponseRedirect(getContext(request, 'cancelUrl')) if 'save-submit' in request.POST: return HttpResponseRedirect('.') for ab in getattr(form, 'additional_buttons', []): if ab[3:] and ab[0] in request.POST: return ab[3](request, instance) else: form = ModelFormClass(instance=instance, button_mask=EDIT_BUTTONS) form_context = {} form_context.update(locals()) form_context.update(additional_context) return render(request, template or 'generic_form.html', form_context)
def allowed(self, request, volume=None): usages = quotas.tenant_quota_usages(request, targets=('volumes', 'gigabytes')) gb_available = usages['gigabytes']['available'] volumes_available = usages['volumes']['available'] if gb_available <= 0 or volumes_available <= 0: if "disabled" not in self.classes: self.classes = [c for c in self.classes] + ['disabled'] self.verbose_name = format_lazy( '{verbose_name} {quota_exceeded}', verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) else: self.verbose_name = _("Accept Transfer") classes = [c for c in self.classes if c != "disabled"] self.classes = classes return True
def get_permission_denied_message(self, object, context_omitted=False): if not context_omitted: countries = [self.get_location(object)] if not countries[0]: countries = self.get_owner(object).owned_places.filter( deleted=False).values_list('country', flat=True) elif not countries[0].name: countries = [] else: countries = None if not countries: return _("Only administrators can access this page") to_string = lambda item: str(Country(item).name) join_lazy = keep_lazy_text( lambda items: ", ".join(map(to_string, items))) return format_lazy(self.permission_denied_message, this_country=join_lazy(countries))
def allowed(self, request, fip=None): usages = quotas.tenant_quota_usages(request, targets=('floatingip', )) if 'floatingip' in usages and usages['floatingip']['available'] <= 0: if "disabled" not in self.classes: self.classes = list(self.classes) + ['disabled'] self.verbose_name = format_lazy( '{verbose_name} {quota_exceeded}', verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) else: self.verbose_name = _("Allocate IP To Project") classes = [c for c in self.classes if c != "disabled"] self.classes = classes policy_rules = (("network", "create_floatingip"),) return policy.check(policy_rules, request)
def allowed(self, request, volume=None): try: limits = api.cinder.tenant_absolute_limits(request) except Exception: exceptions.handle(request, _('Unable to retrieve tenant limits.')) limits = {} snapshots_available = (limits.get('maxTotalSnapshots', float("inf")) - limits.get('totalSnapshotsUsed', 0)) if snapshots_available <= 0 and "disabled" not in self.classes: self.classes = [c for c in self.classes] + ['disabled'] self.verbose_name = format_lazy( '{verbose_name} {quota_exceeded}', verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) return volume.status in ("available", "in-use")
def get(self, request, id): try: deck = Deck.objects.get_by_shortid(id) except Deck.DoesNotExist: raise Http404(_("Deck does not exist.")) cards = deck.card_dbf_id_list() if len(cards) != 30: raise Http404(_("Deck list is too small.")) for card in deck.cards.all(): if not card.collectible: raise Http404(_("Deck list contains uncollectible cards.")) deck_name = _(str(deck)) request.head.title = deck_name if deck.deck_class: request.head.add_meta( { "property": "x-hearthstone:deck", "content": deck_name }, { "property": "x-hearthstone:deck:deckstring", "content": deck.deckstring }, ) self.request.head.add_meta({ "name": "description", "content": format_lazy( _("{name} stats and decklist. Import it: {deckstring}"), name=deck_name, deckstring=deck.deckstring), }) context = { "deck": deck, "deck_name": deck_name, "deck_is_wild": 1 if deck.format == FormatType.FT_WILD else 0, "card_list": ",".join(str(id) for id in cards), } return render(request, self.template_name, context)
def get_react_context(self): region = self.kwargs.get("region", 0) lo = self.kwargs.get("lo", 0) try: account = BlizzardAccount.objects.get(region=region, account_lo=lo) except BlizzardAccount.DoesNotExist: return {} self.request.head.title = format_lazy( _("{user}'s Hearthstone Collection"), user=str(account.battletag)) return { "region": region, "account_lo": lo, "owner": False, "battletag": account.battletag, }
def __init__(self, project, user_id, **kwargs): super(SetUserPasswordForm, self).__init__(**kwargs) self.project = project initial_password = '' if self.project.strong_mobile_passwords: self.fields['new_password1'].widget = forms.TextInput() self.fields['new_password1'].help_text = mark_safe_lazy( format_lazy( ('<i class="fa fa-warning"></i>{}<br />' '<span data-bind="text: passwordHelp, css: color">'), ugettext_lazy( "This password is automatically generated. " "Please copy it or create your own. It will not be shown again."), ) ) initial_password = generate_strong_password() self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_action = reverse("change_password", args=[project.name, user_id]) self.helper.layout = crispy.Layout( crispy.Fieldset( _("Reset Password for Mobile Worker"), crispy.Field( 'new_password1', data_bind="initializeValue: password, value: password, valueUpdate: 'input'", value=initial_password, ), crispy.Field( 'new_password2', value=initial_password, ), hqcrispy.FormActions( crispy.ButtonHolder( Submit('submit', _('Reset Password')) ) ), css_class="check-password", ), )
def get(self, request, *args, **kwargs): try: profile = Profile.get_basic_data(user=request.user) settings_url = reverse_lazy('profile_settings', kwargs={ 'pk': profile.pk, 'slug': profile.autoslug }) except Profile.DoesNotExist: settings_url = reverse_lazy('account_settings') return HttpResponseRedirect( format_lazy( '{settings_url}#{section_email}', settings_url=settings_url, section_email=pgettext_lazy("URL", "email-addr"), ))
def to_python(self, value): if value and len(value): items = value.split(",") else: items = [] errors = [] values = set() for i, item in enumerate(items, start=1): if not len(item): errors.append( ValidationError( self.error_messages['no_double_commas'], code='no_double_commas', )) continue try: value = self.base_field.to_python(item) except ValidationError as e: for error in e.error_list: errors.append( ValidationError( format_lazy( '{}{}', self.error_messages['item_n_invalid'], error.message, ), code='item_n_invalid', params={'nth': i}, )) if value in values: errors.append( ValidationError( self.error_messages['no_duplicates'], code='no_duplicates', params={'item': item}, )) else: values.add(value) if errors: raise ValidationError(errors) return values
def get_meta_options(self, model): """ Returns a dictionary of fields that will be added to the Meta inner class of the historical record model. """ meta_fields = { "ordering": ("-history_date", "-history_id"), "get_latest_by": "history_date", } if self.user_set_verbose_name: name = self.user_set_verbose_name else: name = format_lazy("historical {}", smart_str(model._meta.verbose_name)) meta_fields["verbose_name"] = name if self.app: meta_fields["app_label"] = self.app return meta_fields
def full_list(self): result = [ ("all", _("All strings"), ""), ("readonly", _("Read-only strings"), "state:read-only"), ("nottranslated", _("Untranslated strings"), "state:empty"), ("todo", _("Unfinished strings"), "state:<translated"), ("translated", _("Translated strings"), "state:>=translated"), ("fuzzy", _("Strings marked for edit"), "state:needs-editing"), ("suggestions", _("Strings with suggestions"), "has:suggestion"), ("variants", _("Strings with variants"), "has:variant"), ("labels", _("Strings with labels"), "has:label"), ("context", _("Strings with context"), "has:context"), ( "nosuggestions", _("Unfinished strings without suggestions"), "state:<translated AND NOT has:suggestion", ), ("comments", _("Strings with comments"), "has:comment"), ("allchecks", _("Strings with any failing checks"), "has:check"), ( "translated_checks", _("Translated strings with any failing checks"), "has:check AND state:>=translated", ), ( "dismissed_checks", _("Translated strings with dismissed checks"), "has:dismissed-check", ), ("approved", _("Approved strings"), "state:approved"), ( "approved_suggestions", _("Approved strings with suggestions"), "state:approved AND has:suggestion", ), ("unapproved", _("Strings waiting for review"), "state:translated"), ("unlabeled", _("Strings without a label"), "NOT has:label"), ("pluralized", _("Pluralized string"), "has:plural"), ] result.extend(( CHECKS[check].url_id, format_lazy(_("Failing check: {}"), CHECKS[check].name), f"check:{check}", ) for check in CHECKS) return result
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) config = SiteConfiguration.get_solo() self.helper = FormHelper(self) self.fields['first_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['last_name'].widget.attrs['inputmode'] = 'latin-name' self.fields['names_inversed'].label = _("Names ordering") self.helper['names_inversed'].wrap( InlineRadios, radio_label_class='person-full-name') field_bd = self.fields['birth_date'] if self.instance.has_places_for_hosting or self.instance.has_places_for_meeting: if self.instance.has_places_for_hosting: message = _( "The minimum age to be allowed hosting is {age:d}.") allowed_age = config.host_min_age else: message = _( "The minimum age to be allowed meeting with visitors is {age:d}." ) allowed_age = config.meet_min_age message = format_lazy(message, age=allowed_age) field_bd.required = True field_bd.validators.append(TooNearPastValidator(allowed_age)) # We have to manually create a copy of the error messages dict because Django does not do it: # https://code.djangoproject.com/ticket/30839#ticket field_bd.error_messages = deepcopy(field_bd.error_messages) field_bd.error_messages['max_value'] = message field_bd.widget.attrs['placeholder'] = 'jjjj-mm-tt' field_bd.widget.attrs['data-date-end-date'] = '0d' field_bd.widget.attrs[ 'pattern'] = '[1-2][0-9]{3}-((0[1-9])|(1[0-2]))-((0[1-9])|([12][0-9])|(3[0-1]))' if self.instance.has_places_for_in_book: message = _("This field is required to be printed in the book.") for field in self._validation_meta.book_required_fields: req_field = self.fields[field] req_field.required = True # We have to manually create a copy of the error messages dict because Django does not do it: # https://code.djangoproject.com/ticket/30839#ticket req_field.error_messages = deepcopy(req_field.error_messages) req_field.error_messages['required'] = message req_field.widget.attrs['data-error-required'] = message self.fields['avatar'].widget.attrs['accept'] = 'image/*'
class RequestReviewFormBase(UserAwareModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['target_registration_state'].choices = BLANK_CHOICE_DASH + MDR.STATES self.fields['concepts'].queryset = self.fields['concepts'].queryset.all().visible(self.user) self.fields['concepts'].widget.choices = self.fields['concepts'].choices self.fields['concepts'].label = "Metadata" cascade_registration = forms.ChoiceField( initial=0, choices=CASCADE_OPTIONS_PLURAL, label=_("Cascade registration"), help_text=format_lazy( "{} {}", CASCADE_HELP_TEXT, _('When enabled, see the full list of metadata under the "Impact" tab.') ), widget=forms.RadioSelect(), ) class Meta: model = models.ReviewRequest fields = [ 'title', 'due_date', 'target_registration_state', 'registration_date', 'concepts', 'cascade_registration' ] widgets = { 'title': forms.Textarea(attrs={"rows": "1"}), 'target_registration_state': forms.Select, 'due_date': BootstrapDateTimePicker(options={"format": "YYYY-MM-DD"}), 'registration_date': BootstrapDateTimePicker(options={"format": "YYYY-MM-DD"}), 'concepts': ConceptAutocompleteSelectMultiple(), 'cascade_registration': forms.RadioSelect(), } help_texts = { 'target_registration_state': "The state for endorsement for metadata in this review", 'due_date': "Date this review needs to be actioned by", 'registration_date': "Date the metadata will be endorsed at", 'title': "A short title for this review", 'concepts': "List of metadata for review", 'cascade_registration': "Include related items when registering metadata. When enabled, see the full list of metadata under the \"impact\" tab.", }
def get_meta_options(self, model): """ Returns a dictionary of fields that will be added to the Meta inner class of the edit suggestion record model. """ meta_fields = { "ordering": ("-edit_suggestion_date_created", ), "get_latest_by": "edit_suggestion_date_created", } if self.user_set_verbose_name: name = self.user_set_verbose_name else: name = format_lazy("edit suggestion {}", smart_str(model._meta.verbose_name)) meta_fields["verbose_name"] = name if self.app: meta_fields["app_label"] = self.app return meta_fields
def contribute_to_class(field, cls, fieldclass, **kw): "Used by both :class:`BabelCharField` and :class:`BabelTextField` " if cls._meta.abstract: return kw.update(blank=True) if "__fake__" in repr(cls): # Used to test if we're creating a migration, in that case we don't want to add new fields, # As they're already detected during site startup. return for lang in settings.SITE.BABEL_LANGS: kw.update(verbose_name=format_lazy(u"{}{}", field.verbose_name, ' (' + lang.django_code + ')')) newfield = fieldclass(**kw) #~ newfield._lino_babel_field = True # used by dbtools.get_data_elems newfield._lino_babel_field = field.name newfield._babel_language = lang cls.add_to_class(six.text_type(field.name + '_' + lang.name), newfield)
def form_valid(self, form): # first check the captcha if not verify_captcha(self.request): return redirect('home') email = form.cleaned_data['email'] if Member.objects.filter(email=email).count() > 0: messages.info( self.request, format_lazy(_( 'An account associated with {email} already exists. You can recover this account via the "Forgot Password?" link below.' ), email=email)) return redirect('home') Invite.objects.create(band=None, email=email) return render(self.request, 'member/signup_pending.html', {'email': email})
def value_from_datadict(self, data, files, name): value = data.get(name, None) if value: if isinstance(value, str): value = value.lower() if value not in ('true', 'false', '1', '0'): reason = _('is invalid request parameter. Could be true, false, 1, 0') raise ValidationError({ name: format_lazy('{value} {reason}', value=value, reason=reason) }) return { '1': True, '0': False, 'true': True, 'false': False, True: True, False: False, }.get(value, None)
def create_field_for_both_languages(field_type: Type[Field], pretty_name: str, **kwargs) -> Tuple[Field, Field]: """ helper for making the same textfield for danish and english. :param field_type: :param pretty_name: :param kwargs: :return: a 2-tuple of two fields """ ret: Tuple[Field, Field] = tuple( field_type( format_lazy("{pretty_name} [{lang}]", pretty_name=pretty_name, lang=lang), **kwargs) for lang in [ugettext_lazy("Danish"), ugettext_lazy("English")]) return ret
def add_deviation(self, exercise, profile, minutes, without_late_penalty): try: deviation = DeadlineRuleDeviation.objects.create( exercise=exercise, submitter=profile, granter=self.request.user.userprofile, extra_minutes=minutes, without_late_penalty=without_late_penalty, ) except IntegrityError: messages.warning( self.request, format_lazy( _('DEVIATION_WARNING_DEADLINE_DEVIATION_ALREADY_FOR -- {user}, {exercise}' ), user=str(profile), exercise=str(exercise), ))
def clean(self): cleaned_data = super(PlaceForm, self).clean() # Verifies that user is of correct age if they want to host or meet guests. is_hosting = cleaned_data['available'] is_meeting = cleaned_data['tour_guide'] or cleaned_data['have_a_drink'] if any([is_hosting, is_meeting]): profile = self.profile if hasattr(self, 'profile') else self.instance.owner try: allowed_age = settings.HOST_MIN_AGE if is_hosting else settings.MEET_MIN_AGE TooNearPastValidator(allowed_age)(profile.birth_date or date.today()) except forms.ValidationError: if is_hosting: self.add_error('available', "") message = _("The minimum age to be allowed hosting is {age:d}.") else: if cleaned_data['tour_guide']: self.add_error('tour_guide', "") if cleaned_data['have_a_drink']: self.add_error('have_a_drink', "") message = _("The minimum age to be allowed meeting with visitors is {age:d}.") raise forms.ValidationError(format_lazy(message, age=allowed_age)) # Sets some fields as required if user wants their data to be printed in book. required_fields = ['address', 'city', 'closest_city', 'country', 'available', 'latitude', 'longitude'] all_filled = all([cleaned_data.get(field, False) for field in required_fields]) message = _("You want to be in the printed edition of Pasporta Servo. " "In order to have a quality product, some fields a required. " "If you think there is a problem, please contact us.") if cleaned_data['in_book'] and not all_filled: for field in required_fields: if not cleaned_data['latitude'] or not cleaned_data['longitude']: raise forms.ValidationError(_("Please click on the map to choose your location.")) if not cleaned_data.get(field, False): self.add_error(field, _("This field is required to be printed in the book.")) raise forms.ValidationError(message) return cleaned_data
def test_format_lazy(self): self.assertEqual("django/test", format_lazy("{}/{}", "django", lazystr("test"))) self.assertEqual("django/test", format_lazy("{0}/{1}", *("django", "test"))) self.assertEqual("django/test", format_lazy("{a}/{b}", **{"a": "django", "b": "test"})) self.assertEqual("django/test", format_lazy("{a[0]}/{a[1]}", a=("django", "test"))) t = {} s = format_lazy("{0[a]}-{p[a]}", t, p=t) t["a"] = lazystr("django") self.assertEqual("django-django", s) t["a"] = "update" self.assertEqual("update-update", s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy(ugettext_lazy('Added {name} "{object}".'), name="article", object="My first try") with override("fr"): self.assertEqual("article «\xa0My first try\xa0» ajouté.", s)
def post(self, request, *args, **kwargs): if self.round.draw_status != Round.STATUS_CONFIRMED: return HttpResponseBadRequest("Draw status is not CONFIRMED") self.round.draw_status = Round.STATUS_RELEASED self.round.save() self.log_action() email_success_message = "" if self.tournament.pref('enable_adj_email'): try: send_mail_to_adjs(self.round) except SMTPException: messages.error(self.request, _("There was a problem sending adjudication assignment emails.")) except ConnectionError as e: messages.error(self.request, _( "There was a problem connecting to the e-mail server when trying to send adjudication assigment emails: %(error)s" ) % {'error': str(e)}) else: email_success_message = _("Adjudicator emails successfully sent.") messages.success(request, format_lazy(_("Released the draw."), " ", email_success_message)) return super().post(request, *args, **kwargs)