我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.translation.ugettext()。
def __fields__(self, info): lang = get_language_database() fields = [] fields.append(('product__family__{}__name'.format(lang), _("Family"))) fields.append(('product__category__{}__name'.format(lang), _("Category"))) fields.append(('product__subcategory__{}__name'.format(lang), _("Subcategory"))) fields.append(('code', _("Code"))) fields.append(('product__code', _("Product Code"))) fields.append(('{}__name'.format(lang), _("Product"))) fields.append(('{}__public'.format(lang), _("Public"))) fields.append(('stock_real', _("Stock real"))) fields.append(('stock_lock', _("Stock lock"))) fields.append(('price', _("Price"))) fields.append(('is_pack', _("Is pack"))) fields.append(('sample', _("Sample"))) return fields
def __fields__(self, info): lang = get_language_database() fields = [] fields.append(('name:{}__name'.format(lang), _("Name"))) fields.append(('slug:{}__slug'.format(lang), _("Slug"))) fields.append(('products_image__image', _("Image"))) fields.append(('products_image__principal', _("Principal"))) # fields.append(('productfinals_image__image', _("Image"))) # fields.append(('productfinals_image__principal', _("Principal"))) # fields.append(('price', _("Price"))) # fields.append(('price_old:price', _("Price"))) # fields.append(('offer', _("Offer"))) fields.append(('created', _("Created"))) # fields.append(('reviews_value', _("reviews_value"))) # fields.append(('reviews_count', _("reviews_count"))) return fields
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is None: messages.error(request, _('No user account matches the entered credentials.')) return redirect('common:login') if not user.is_active: messages.error(request, _('User account is deactivated.')) return redirect('common:login') login(request, user) url = urllib.parse.unquote(request.GET.get('next', '')) if url and is_safe_url(url, request.get_host()): return redirect(url) return redirect('/')
def clean_rename_format(self): try: self.cleaned_data['rename_format'] % { 'original_filename': 'filename', 'original_basename': 'basename', 'original_extension': 'ext', 'current_filename': 'filename', 'current_basename': 'basename', 'current_extension': 'ext', 'current_folder': 'folder', 'counter': 42, 'global_counter': 42, } except KeyError as e: raise forms.ValidationError(_('Unknown rename format value key "%(key)s".') % {'key': e.args[0]}) except Exception as e: raise forms.ValidationError(_('Invalid rename format: %(error)s.') % {'error': e}) return self.cleaned_data['rename_format']
def management_form(self): """Returns the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( _('ManagementForm data is missing or has been tampered with'), code='missing_management_form', ) else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num }) return form
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, field_order=None): self.is_bound = data is not None or files is not None self.data = data or {} self.files = files or {} self.auto_id = auto_id if prefix is not None: self.prefix = prefix self.initial = initial or {} self.error_class = error_class # Translators: This is the default suffix added to form field labels self.label_suffix = label_suffix if label_suffix is not None else _(':') self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields) self._bound_fields_cache = {} self.order_fields(self.field_order if field_order is None else field_order)
def render(self, name, value, attrs): encoded = value final_attrs = self.build_attrs(attrs) if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX): summary = mark_safe("<strong>%s</strong>" % ugettext("No password set.")) else: try: hasher = identify_hasher(encoded) except ValueError: summary = mark_safe("<strong>%s</strong>" % ugettext( "Invalid password format or unknown hashing algorithm.")) else: summary = format_html_join('', "<strong>{}</strong>: {} ", ((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items()) ) return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def validate(self, password, user=None): if not user: return for attribute_name in self.user_attributes: value = getattr(user, attribute_name, None) if not value or not isinstance(value, string_types): continue value_parts = re.split('\W+', value) + [value] for value_part in value_parts: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name) raise ValidationError( _("The password is too similar to the %(verbose_name)s."), code='password_too_similar', params={'verbose_name': verbose_name}, )
def apnumber(value): """ For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 < value < 10: return value return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'), _('seven'), _('eight'), _('nine'))[value - 1] # Perform the comparison in the default time zone when USE_TZ = True # (unless a specific time zone has been applied with the |timezone filter).
def feed(request, url, feed_dict=None): """Provided for backwards compatibility.""" if not feed_dict: raise Http404(_("No feeds are registered.")) slug = url.partition('/')[0] try: f = feed_dict[slug] except KeyError: raise Http404(_("Slug %r isn't registered.") % slug) instance = f() instance.feed_url = getattr(f, 'feed_url', None) or request.path instance.title_template = f.title_template or ('feeds/%s_title.html' % slug) instance.description_template = f.description_template or ('feeds/%s_description.html' % slug) return instance(request)
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict(self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def formfield_for_choice_field(self, db_field, request=None, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if 'widget' not in kwargs: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) if 'choices' not in kwargs: kwargs['choices'] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[('', _('None'))] ) return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs)
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. """ paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if (self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists')): is_empty = not self.object_list.exists() else: is_empty = len(self.object_list) == 0 if is_empty: raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {'class_name': self.__class__.__name__}) context = self.get_context_data() return self.render_to_response(context)
def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() paginate_by = self.get_paginate_by(qs) if not allow_future: now = timezone.now() if self.uses_datetime_field else timezone_today() qs = qs.filter(**{'%s__lte' % date_field: now}) if not allow_empty: # When pagination is enabled, it's better to do a cheap query # than to load the unpaginated queryset in memory. is_empty = len(qs) == 0 if paginate_by is None else not qs.exists() if is_empty: raise Http404(_("No %(verbose_name_plural)s available") % { 'verbose_name_plural': force_text(qs.model._meta.verbose_name_plural) }) return qs
def default_urlconf(request): "Create an empty URLconf 404 error response." t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE) c = Context({ "title": _("Welcome to Django"), "heading": _("It worked!"), "subheading": _("Congratulations on your first Django-powered page."), "instructions": _("Of course, you haven't actually done any work yet. " "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."), "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your " "Django settings file and you haven't configured any URLs. Get to work!"), }) return HttpResponse(t.render(c), content_type='text/html') # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. #
def render(self, name, value, attrs): encoded = value final_attrs = self.build_attrs(attrs) if not encoded or encoded.startswith(UNUSABLE_PASSWORD_PREFIX): summary = mark_safe("<strong>%s</strong>" % ugettext("No password set.")) else: try: hasher = identify_hasher(encoded) except ValueError: summary = mark_safe("<strong>%s</strong>" % ugettext( "Invalid password format or unknown hashing algorithm." )) else: summary = format_html_join( '', '<strong>{}</strong>: {} ', ((ugettext(key), value) for key, value in hasher.safe_summary(encoded).items()) ) return format_html("<div{}>{}</div>", flatatt(final_attrs), summary)
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict( self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def disconnect(request, backend, association_id=None): associated = request.user.social_auth.count() url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or backend_setting(backend, 'SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') or DEFAULT_REDIRECT if not request.user.has_usable_password() and associated <= 1: messages.error(request, _("Cannot remove the only Social Account without first setting a Password or adding another Social Account.")) return HttpResponseRedirect(url) usa = request.user.social_auth.get(pk=association_id) backend.disconnect(request.user, association_id) messages.success(request, _("Removed the %(provider)s account '%(uid)s'.") % { "provider": usa.provider, "uid": usa.extra_data.get("display", usa.uid) if usa.extra_data is not None else usa.uid, }) return HttpResponseRedirect(url)
def get_context(self): """ Prepare the context for templates. """ self.title = _('%s List') % force_text(self.opts.verbose_name) model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f)) for f in (list(self.opts.fields) + self.get_model_method_fields()) if f.name not in self.list_exclude] new_context = { 'model_name': force_text(self.opts.verbose_name_plural), 'title': self.title, 'cl': self, 'model_fields': model_fields, 'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]), 'has_add_permission': self.has_add_permission(), 'app_label': self.app_label, 'brand_name': self.opts.verbose_name_plural, 'brand_icon': self.get_model_icon(self.model), 'add_url': self.model_admin_url('add'), 'result_headers': self.result_headers(), 'results': self.results() } context = super(ListAdminView, self).get_context() context.update(new_context) return context
def get_context(self): new_context = { 'title': _('%s Detail') % force_text(self.opts.verbose_name), 'form': self.form_obj, 'object': self.obj, 'has_change_permission': self.has_change_permission(self.obj), 'has_delete_permission': self.has_delete_permission(self.obj), 'content_type_id': ContentType.objects.get_for_model(self.model).id, } context = super(DetailAdminView, self).get_context() context.update(new_context) return context
def init_request(self, object_id, *args, **kwargs): "The 'delete' admin view for this model." self.obj = self.get_object(unquote(object_id)) if not self.has_delete_permission(self.obj): raise PermissionDenied if self.obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)}) using = router.db_for_write(self.model) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects( [self.obj], self.opts, self.request.user, self.admin_site, using)
def get_context(self): if self.perms_needed or self.protected: title = _("Cannot delete %(name)s") % {"name": force_text(self.opts.verbose_name)} else: title = _("Are you sure?") new_context = { "title": title, "object": self.obj, "deleted_objects": self.deleted_objects, "perms_lacking": self.perms_needed, "protected": self.protected, } context = super(DeleteAdminView, self).get_context() context.update(new_context) return context
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: self.user_cache = authenticate( username=username, password=password) if self.user_cache is None: if u'@' in username: User = get_user_model() # Mistakenly entered e-mail address instead of username? Look it up. try: user = User.objects.get(email=username) except (User.DoesNotExist, User.MultipleObjectsReturned): # Nothing to do here, moving along. pass else: if user.check_password(password): message = _("Your e-mail address is not your username." " Try '%s' instead.") % user.username raise forms.ValidationError(message) elif not self.user_cache.is_active or not self.user_cache.is_staff: raise forms.ValidationError(message) return self.cleaned_data
def do_post(self, __): def _method(): self.revision_context_manager.set_user(self.user) comment = '' admin_view = self.admin_view if isinstance(admin_view, CreateAdminView): comment = _(u"Initial version.") elif isinstance(admin_view, UpdateAdminView): comment = _(u"Change version.") elif isinstance(admin_view, RevisionView): comment = _(u"Revert version.") elif isinstance(admin_view, RecoverView): comment = _(u"Rercover version.") elif isinstance(admin_view, DeleteAdminView): comment = _(u"Deleted %(verbose_name)s.") % { "verbose_name": self.opts.verbose_name} self.revision_context_manager.set_comment(comment) return __() return _method
def get_form_helper(self): helper = super(RevisionView, self).get_form_helper() diff_fields = {} version_data = self.version.field_dict for f in self.opts.fields: fvalue = f.value_from_object(self.org_obj) vvalue = version_data.get(f.name, None) if fvalue is None and vvalue == '': vvalue = None if is_related_field2(f): vvalue = version_data.get(f.name + '_' + f.rel.get_related_field().name, None) if fvalue != vvalue: diff_fields[f.name] = self.detail.get_field_result(f.name).val for k, v in diff_fields.items(): helper[k].wrap(DiffField, orgdata=v) return helper
def get_related_versions(self, obj, version, formset): """Retreives all the related Version objects for the given FormSet.""" object_id = obj.pk # Get the fk name. try: fk_name = formset.fk.name + '_' + formset.fk.rel.get_related_field().name except AttributeError: # This is a GenericInlineFormset, or similar. fk_name = formset.ct_fk_field.name # Look up the revision data. revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version) for related_version in revision_versions if ContentType.objects.get_for_id(related_version.content_type_id).model_class() == formset.model and smart_text(related_version.field_dict[fk_name]) == smart_text(object_id)]) return related_versions
def block_top_navbar(self, context, nodes): search_models = [] site_name = self.admin_site.name if self.global_search_models == None: models = self.admin_site._registry.keys() else: models = self.global_search_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "view"): info = (app_label, model._meta.model_name) if getattr(self.admin_site._registry[model], 'search_fields', None): try: search_models.append({ 'title': _('Search %s') % capfirst(model._meta.verbose_name_plural), 'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR}))
def block_top_navmenu(self, context, nodes): add_models = [] site_name = self.admin_site.name if self.global_add_models == None: models = self.admin_site._registry.keys() else: models = self.global_add_models for model in models: app_label = model._meta.app_label if self.has_model_perm(model, "add"): info = (app_label, model._meta.model_name) try: add_models.append({ 'title': _('Add %s') % capfirst(model._meta.verbose_name), 'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name), 'model': model }) except NoReverseMatch: pass nodes.append( loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models}))
def result_item(self, item, obj, field_name, row): if self.list_editable and item.field and item.field.editable and (field_name in self.list_editable): pk = getattr(obj, obj._meta.pk.attname) field_label = label_for_field(field_name, obj, model_admin=self.admin_view, return_attr=False ) item.wraps.insert(0, '<span class="editable-field">%s</span>') item.btns.append(( '<a class="editable-handler" title="%s" data-editable-field="%s" data-editable-loadurl="%s">' + '<i class="fa fa-edit"></i></a>') % (_(u"Enter %s") % field_label, field_name, self.admin_view.model_admin_url('patch', pk) + '?fields=' + field_name)) if field_name not in self.editable_need_fields: self.editable_need_fields[field_name] = item.field return item # Media
def setup(self): super(ChartWidget, self).setup() self.charts = {} self.one_chart = False model_admin = self.admin_site._registry[self.model] chart = self.chart if hasattr(model_admin, 'data_charts'): if chart and chart in model_admin.data_charts: self.charts = {chart: model_admin.data_charts[chart]} self.one_chart = True if self.title is None: self.title = model_admin.data_charts[chart].get('title') else: self.charts = model_admin.data_charts if self.title is None: self.title = ugettext( "%s Charts") % self.model._meta.verbose_name_plural
def build_attrs(self, attrs={}, **kwargs): to_opts = self.rel.to._meta if "class" not in attrs: attrs['class'] = 'select-search' else: attrs['class'] = attrs['class'] + ' select-search' attrs['data-search-url'] = self.admin_view.get_admin_url( '%s_%s_changelist' % (to_opts.app_label, to_opts.model_name)) attrs['data-placeholder'] = _('Search %s') % to_opts.verbose_name attrs['data-choices'] = '?' if self.rel.limit_choices_to: for i in list(self.rel.limit_choices_to): attrs['data-choices'] += "&_p_%s=%s" % (i, self.rel.limit_choices_to[i]) attrs['data-choices'] = format_html(attrs['data-choices']) return super(ForeignKeySearchWidget, self).build_attrs(attrs, **kwargs)
def __fields__(self, info): fields = [] fields.append(('category', _("Category"))) fields.append(('subcategory', _("Subcategory"))) fields.append(('code', _("Code"))) fields.append(('{}__name'.format(self.lang), _("Name"))) fields.append(('public', _("Public"))) fields.append(('tax', _("Tax"))) fields.append(('price_base', _("Price base"))) fields.append(('of_sales', _("Of sales"))) fields.append(('of_purchase', _("Of purchase"))) fields.append(('force_stock', _("Force stock"))) fields.append(('feature_special', _("Feature special"))) return fields
def __searchF__(self, info): lang = get_language_database() fields = {} fields['{}__name'.format(lang)] = (_('Name'), lambda x, lang=lang: Q(**{'{}__name__icontains'.format(lang): x}), 'input') fields['category'] = (_('Category'), lambda x, lang=lang: Q(**{'category__{}__name__icontains'.format(lang): x}), 'input') fields['subcategory'] = (_('Subcategory'), lambda x, lang=lang: Q(**{'subcategory__{}__name__icontains'.format(lang): x}), 'input') return fields
def __fields__(self, info): fields = [] fields.append(('name:{}__name'.format(self.lang), _("Name"))) fields.append(('slug:{}__slug'.format(self.lang), _("Slug"))) fields.append(('outstanding', _("Outstanding"))) fields.append(('show_menu', _("Show menu"))) fields.append(('order', _("Order"))) return fields
def __fields__(self, info): fields = [] fields.append(('order', _("Order"))) fields.append(('public', _("Public"))) fields.append(('principal', _("Principal"))) fields.append(('image', _("Image"), None, None, 'image:width:66px')) return fields
def form_valid(self, form): attribute = form.cleaned_data['attribute'] if attribute.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif attribute.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif attribute.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueAttribute.objects.filter( pk=value, group__attributes=attribute ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureCreate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureCreate, self).form_invalid(form) self.request.value = value form.instance.value = value if self.__product_pk: product = ProductFinal.objects.get(pk=self.__product_pk) self.request.product = product form.instance.product = product return super(ProductFinalAttributeCreate, self).form_valid(form)
def form_valid(self, form): attribute = form.cleaned_data['attribute'] if attribute.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif attribute.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif attribute.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueAttribute.objects.filter( pk=value, group__attributes=attribute ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFinalAttributeUpdate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFinalAttributeUpdate, self).form_invalid(form) self.request.value = value form.instance.value = value return super(ProductFinalAttributeUpdate, self).form_valid(form)
def form_valid(self, form): feature = form.cleaned_data['feature'] if feature.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif feature.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif feature.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueFeature.objects.filter( pk=value, group__features=feature ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureCreate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureCreate, self).form_invalid(form) self.request.value = value form.instance.value = value if self.__product_pk: product = Product.objects.get(pk=self.__product_pk) self.request.product = product form.instance.product = product return super(ProductFeatureCreate, self).form_valid(form)
def form_valid(self, form): feature = form.cleaned_data['feature'] if feature.type_value == TYPE_VALUE_BOOLEAN: value = int(form.cleaned_data['value_bool']) elif feature.type_value == TYPE_VALUE_FREE: value = form.cleaned_data['value_free'] elif feature.type_value == TYPE_VALUE_LIST: value = form.cleaned_data['value_list'] if not OptionValueFeature.objects.filter( pk=value, group__features=feature ).exists(): errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Option invalid')) return super(ProductFeatureUpdate, self).form_invalid(form) else: value = None if value is None: errors = form._errors.setdefault("value", ErrorList()) errors.append(_('Value invalid')) return super(ProductFeatureUpdate, self).form_invalid(form) self.request.value = value form.instance.value = value return super(ProductFeatureUpdate, self).form_valid(form)
def form_valid(self, form): try: return super(ProductUniqueUpdate, self).form_valid(form) except ValidationError as e: errors = form._errors.setdefault("value", ErrorList()) errors.append(e) return super(ProductUniqueCreate, self).form_invalid(form) except IntegrityError: errors = form._errors.setdefault("value", ErrorList()) errors.append(_("Value existing")) return super(ProductUniqueUpdate, self).form_invalid(form)
def __fields__(self, info): fields = [] fields.append(('name:es__name', _("Name"))) fields.append(('slug:es__slug', _("Slug"))) fields.append(('product__products_image__image', _("Image"))) fields.append(('product__products_image__principal', _("Principal"))) fields.append(('productfinals_image__image', _("Image"))) fields.append(('productfinals_image__principal', _("Principal"))) fields.append(('price', _("Price"))) # fields.append(('price_old:price', _("Price"))) fields.append(('offer', _("Offer"))) fields.append(('created', _("Created"))) fields.append(('reviews_value', _("Reviews"))) fields.append(('reviews_count', _("Reviews count"))) return fields
def saml_register(saml_id, user_attributes, token=None): auth_data_model = apps.get_model('users', 'AuthData') user_model = apps.get_model('users', 'User') try: # SAML user association exist? auth_data = auth_data_model.objects.get(key="saml", value=saml_id) user = auth_data.user except auth_data_model.DoesNotExist: try: # Is a there a user with the same email as the SAML user? user = user_model.objects.get(email=user_attributes['email']) auth_data_model.objects.create(user=user, key='saml', value=saml_id, extra={}) except user_model.DoesNotExist: # Create a new user user_attributes['username'] = slugify_uniquely(user_attributes['username'], user_model, slugfield='username') user = user_model.objects.create(**user_attributes) auth_data_model.objects.create(user=user, key='saml', value=saml_id, extra={}) send_register_email(user) user_registered_signal.send(sender=user.__class__, user=user) if token: membership = get_membership_by_token(token) try: membership.user = user membership.save(update_fields=['user']) except IntegrityError: raise exc.IntegrityError(_("This user is already a member of the project.")) return user
def move_to_clipboard(self, request, files_queryset, folders_queryset): """ Action which moves the selected files and files in selected folders to clipboard. """ if not self.has_change_permission(request): raise PermissionDenied if request.method != 'POST': return None clipboard = tools.get_user_clipboard(request.user) check_files_edit_permissions(request, files_queryset) check_folder_edit_permissions(request, folders_queryset) # TODO: Display a confirmation page if moving more than X files to # clipboard? # We define it like that so that we can modify it inside the # move_files function files_count = [0] def move_files(files): files_count[0] += tools.move_file_to_clipboard(files, clipboard) def move_folders(folders): for f in folders: move_files(f.files) move_folders(f.children.all()) move_files(files_queryset) move_folders(folders_queryset) self.message_user(request, _("Successfully moved %(count)d files to " "clipboard.") % {"count": files_count[0]}) return None