Here are the examples of the python api django.utils.encoding.force_unicode taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
149 Examples
3
Example 1
Project: imaginationforpeople Source File: word_boundary_aware_truncate_chars.py
Function: truncate_chars
Function: truncate_chars
def truncate_chars(s, num):
"""
Template filter to truncate a string to at most num characters respecting word
boundaries.
"""
s = force_unicode(s)
length = int(num)
if len(s) > length:
length = length - 4
if s[length-1] == ' ' or s[length] == ' ':
s = s[:length].strip()
else:
words = s[:length].split()
if len(words) > 1:
del words[-1]
s = u' '.join(words)
s += ' ...'
return s
3
Example 2
def load(self):
try:
session_data = self.server.get(
self.get_real_stored_key(self._get_or_create_session_key())
)
return self.decode(force_unicode(session_data))
except:
self._session_key = None
return {}
3
Example 3
@register.filter(is_safe=True)
@stringfilter
def markup(value):
extensions = ["markdown.extensions.nl2br"]
val = force_unicode(value)
html = markdown(val, extensions=extensions, enable_attributes=False)
return mark_safe(html)
3
Example 4
Project: hstore-field Source File: forms.py
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = ''
elif not isinstance(value, unicode):
value = json.dumps(value, indent=2, cls=HstoreEncoder)
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), conditional_escape(force_unicode(value))))
3
Example 5
Project: couchdbkit Source File: schema.py
def verbose_name_raw(self):
"""
There are a few places where the untranslated verbose name is needed
(so that we get the same value regardless of currently active
locale).
"""
lang = get_language()
deactivate_all()
raw = force_unicode(self.verbose_name)
activate(lang)
return raw
3
Example 6
def _strip_tags(value):
"""
Returns the given HTML with all tags stripped.
This is a copy of django.utils.html.strip_tags, except that it adds some
whitespace in between replaced tags to make sure words are not erroneously
concatenated.
"""
return re.sub(r'<[^>]*?>', ' ', force_unicode(value))
3
Example 7
def default(self, o):
if isinstance(o, Promise):
return force_unicode(o)
if isinstance(o, datetime):
return o.strftime('%Y-%m-%dT%H:%M:%S')
if isinstance(o, date):
return o.strftime('%Y-%m-%d')
else:
return super(JSONEncoder, self).default(o)
3
Example 8
def tree_path(items, separator=' :: '):
"""
Creates a tree path represented by a list of ``items`` by joining
the items with a ``separator``.
Each path item will be coerced to unicode, so a list of model
instances may be given if required.
Example::
{{ some_list|tree_path }}
{{ some_node.get_ancestors|tree_path:" > " }}
"""
return separator.join([force_unicode(i) for i in items])
3
Example 9
def get_errors(self):
from django.utils.encoding import force_unicode
output = {}
for key, value in self.errors.items():
output[key] = '/n'.join([force_unicode(i) for i in value])
return output
3
Example 10
Project: django-versions Source File: base.py
def commit(self, changes):
changeset = Changeset()
changeset.message = revision.message
changeset.user = revision.user.id
changeset.save()
for path, data in changes.items():
rev = Revision()
rev.changeset = changeset
rev.path = path
rev.data = force_unicode(data, errors='ignore')
rev.save()
return changeset.pk
3
Example 11
def render(self, name, value, attrs=None):
try:
data = json.loads(force_unicode(value))
except:
data = {}
output = ''
for k,v in data.items():
output += self.render_pair(k, v, name)
output += self.render_pair('', '', name)
return mark_safe(output)
3
Example 12
def get_date_list(self, queryset, date_type):
"""
Get a date list by calling `queryset.dates()`, checking along the way
for empty lists that aren't allowed.
"""
date_field = self.get_date_field()
allow_empty = self.get_allow_empty()
date_list = queryset.dates(date_field, date_type)[::-1]
if date_list is not None and not date_list and not allow_empty:
name = force_unicode(queryset.model._meta.verbose_name_plural)
raise Http404(_(u"No %(verbose_name_plural)s available") % {
'verbose_name_plural': name,
})
return date_list
3
Example 13
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, name=name)
# TODO use the help_text field of edit form instead of rendering a template
return render_to_string('wiki/includes/editor_widget.html',
{'attrs': mark_safe(flatatt(final_attrs)),
'content': conditional_escape(force_unicode(value)),
})
3
Example 14
Project: django-databrowse Source File: calendars.py
def model_index_html(self, request, model, site):
fields = self.field_dict(model)
if not fields:
return u''
return mark_safe(
u'<p class="filter"><strong>View calendar by:</strong> %s</p>' % \
u', '.join(
['<a href="calendars/%s/">%s</a>' %
(f.name,force_unicode(capfirst(f.verbose_name)))
for f in fields.values()])
)
3
Example 15
def get_script_name(environ):
script_url = environ.get('SCRIPT_URL', u'')
if not script_url:
script_url = environ.get('REDIRECT_URL', u'')
if script_url:
return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))])
return force_unicode(environ.get('SCRIPT_NAME', u''))
3
Example 16
Project: aino-convert Source File: convert_tags.py
def render(self, context):
try:
input_file = force_unicode(self.input_file.resolve(context))
options = self.options.resolve(context)
ext = self.ext and self.ext.resolve(context)
if not input_file:
dest = convert_solo(options, ext)
else:
source = MediaFile(input_file)
dest = source.convert(options, ext)
except:
return self.error(context)
return self.success(context, dest)
3
Example 17
Project: ganetimgr Source File: forms.py
def render_option(self, selected_choices, option_value, option_label):
option_value = force_unicode(option_value)
if (option_value in selected_choices):
selected_html = u' selected="selected"'
else:
selected_html = ''
disabled_html = ''
if isinstance(option_label, dict):
if dict.get(option_label, 'disabled'):
disabled_html = u' disabled="disabled"'
option_label = option_label['label']
return u'<option value="%s"%s%s>%s</option>' % (
escape(option_value), selected_html, disabled_html,
conditional_escape(force_unicode(option_label)))
3
Example 18
Project: sikteeri Source File: utils.py
def log_change(object, user, before=None, after=None, change_message=None):
if not change_message:
if before and after:
change_message = diff_humanize(dict_diff(before, after))
else:
change_message = "Some changes were made"
if not change_message:
return
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_unicode(object),
action_flag = CHANGE,
change_message = change_message
)
3
Example 19
Project: reviewboard Source File: base.py
def _get_form_errors(self, form):
fields = {}
for field in form.errors:
fields[field] = [force_unicode(e) for e in form.errors[field]]
return fields
3
Example 20
Project: django-tcms Source File: views.py
def log(request, obj, level, message=''):
"""Log events for user notification"""
ct = ContentType.objects.get_for_model(obj.__class__).pk
try:
object_repr = force_unicode(obj)
except:
object_repr = ''
LogEntry.objects.log_action(user_id=request.user.id, content_type_id=ct,
object_id=obj.pk, object_repr=object_repr,
action_flag=level, change_message=message)
3
Example 21
Project: django-chile-payments Source File: forms.py
def __init__(self, name, value, attrs, choice, index):
super(PaymentRadioInput, self).__init__(name, value, attrs, choice, index)
logo_url = import_name(choice[0]).PaymentProcessor.get_logo_url()
if logo_url:
self.choice_label = mark_safe('<img src="%s%s" alt="%s">' % (
getattr(settings, 'STATIC_URL', ''),
logo_url,
force_unicode(choice[1]),
)
)
3
Example 22
Project: django-pagedown Source File: widgets.py
def render(self, name, value, attrs=None):
if value is None:
value = ""
final_attrs = self.build_attrs(attrs, name=name)
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
3
Example 23
def render_options(self, choices, selected_choices, name):
selected_choices = set(force_unicode(v) for v in selected_choices)
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
for option in option_label:
output.append(self.render_option(name, selected_choices, *option))
else:
output.append(self.render_option(name, selected_choices, option_value, option_label))
return u'\n'.join(output)
3
Example 24
def do_log(self, object_, action_flag, message):
LogEntry.objects.log_action(
user_id=self.user.pk,
content_type_id=ContentType.objects.get_for_model(object_).pk,
object_id=object_.pk,
object_repr=force_unicode(object_),
action_flag=action_flag,
change_message=unicode(message))
3
Example 25
Project: django-fancypages Source File: mixins.py
def render_to_error_response(self, reason, context=None):
if context is None:
context = {}
context['success'] = False
context['reason'] = force_unicode(reason)
return self.render_to_response(context)
3
Example 26
Project: django-localflavor Source File: promises.py
def lazy_repr(obj):
if list_or_tuple(obj):
values = []
for item in obj:
values.append(lazy_repr(item))
if isinstance(obj, tuple):
values = tuple(values)
return values
elif isinstance(obj, dict):
values = {}
for key, value in obj.items():
values[lazy_repr(key)] = lazy_repr(value)
return values
else:
if isinstance(obj, Promise):
obj = force_unicode(obj)
return obj
3
Example 27
Project: Adlibre-TMS Source File: widgets.py
def render(self, name, value, attrs=None):
output = []
if value is None: value = ''
saasu_item_url = '../../../saasu/saasu_item_lookup/'
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(value)
output.append('<input%s />' % flatatt(final_attrs))
output.append('<a href="%s" class="saasu-item-lookup" id="item_lookup_id_%s" onclick="return showSaasuItemLookupPopup(this);">' % (saasu_item_url, name))
output.append('<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" /></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
return mark_safe(u''.join(output))
3
Example 28
def get_request(self, path, data={}, **extra):
"Construct a GET request."
parsed = urlparse(path)
r = {
'CONTENT_TYPE': str('text/html; charset=utf-8'),
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': urlencode(data, doseq=True) or force_unicode(parsed[4]),
'REQUEST_METHOD': str('GET'),
}
r.update(extra)
return WSGIRequest(self._base_environ(**r))
3
Example 29
Project: django-multilingual-ng Source File: admin.py
def response_change(self, request, obj):
# because save & continue - so it shows the same language
if request.POST.has_key("_continue"):
opts = obj._meta
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
self.message_user(request, msg + ' ' + _("You may edit it again below."))
lang, path = request.GET.get('language', get_default_language()), request.path
if lang:
lang = "language=%s" % lang
if request.REQUEST.has_key('_popup'):
path += "?_popup=1" + "&%s" % lang
else:
path += "?%s" % lang
return HttpResponseRedirect(path)
return super(MultilingualModelAdmin, self).response_change(request, obj)
3
Example 30
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if value != '':
try:
final_attrs['value'] = \
force_unicode(value.strftime(self.dformat))
except:
final_attrs['value'] = \
force_unicode(value)
if not final_attrs.has_key('id'):
final_attrs['id'] = u'%s_id' % (name)
id = final_attrs['id']
jsdformat = self.dformat #.replace('%', '%%')
cal = calbtn % (settings.MEDIA_URL, id, id, jsdformat, id)
a = u'<input%s />%s%s' % (forms.util.flatatt(final_attrs), self.media, cal)
return mark_safe(a)
3
Example 31
def html_decode(html):
html = force_unicode(html)
for args in html_codes:
html = html.replace(*args)
return html
0
Example 32
Project: bugle_project Source File: typogrify.py
def widont(text):
"""Replaces the space between the last two words in a string with `` ``
Works in these block tags ``(h1-h6, p, li, dd, dt)`` and also accounts for
potential closing inline elements ``a, em, strong, span, b, i``
>>> widont('A very simple test')
u'A very simple test'
Single word items shouldn't be changed
>>> widont('Test')
u'Test'
>>> widont(' Test')
u' Test'
>>> widont('<ul><li>Test</p></li><ul>')
u'<ul><li>Test</p></li><ul>'
>>> widont('<ul><li> Test</p></li><ul>')
u'<ul><li> Test</p></li><ul>'
>>> widont('<p>In a couple of paragraphs</p><p>paragraph two</p>')
u'<p>In a couple of paragraphs</p><p>paragraph two</p>'
>>> widont('<h1><a href="#">In a link inside a heading</i> </a></h1>')
u'<h1><a href="#">In a link inside a heading</i> </a></h1>'
>>> widont('<h1><a href="#">In a link</a> followed by other text</h1>')
u'<h1><a href="#">In a link</a> followed by other text</h1>'
Empty HTMLs shouldn't error
>>> widont('<h1><a href="#"></a></h1>')
u'<h1><a href="#"></a></h1>'
>>> widont('<div>Divs get no love!</div>')
u'<div>Divs get no love!</div>'
>>> widont('<pre>Neither do PREs</pre>')
u'<pre>Neither do PREs</pre>'
>>> widont('<div><p>But divs with paragraphs do!</p></div>')
u'<div><p>But divs with paragraphs do!</p></div>'
"""
text = force_unicode(text)
widont_finder = re.compile(r"""((?:</?(?:a|em|span|strong|i|b)[^>]*>)|[^<>\s]) # must be proceeded by an approved inline opening or closing tag or a nontag/nonspace
\s+ # the space to replace
([^<>\s]+ # must be flollowed by non-tag non-space characters
\s* # optional white space!
(</(a|em|span|strong|i|b)>\s*)* # optional closing inline tags with optional white space after each
((</(p|h[1-6]|li|dt|dd)>)|$)) # end with a closing p, h1-6, li or the end of the string
""", re.VERBOSE)
output = widont_finder.sub(r'\1 \2', text)
return mark_safe(output)
0
Example 33
def unordered_list(value, autoescape=None):
"""
Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var``
contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``,
then ``{{ var|unordered_list }}`` would return::
<li>States
<ul>
<li>Kansas
<ul>
<li>Lawrence</li>
<li>Topeka</li>
</ul>
</li>
<li>Illinois</li>
</ul>
</li>
"""
if autoescape:
from django.utils.html import conditional_escape
escaper = conditional_escape
else:
escaper = lambda x: x
def convert_old_style_list(list_):
"""
Converts old style lists to the new easier to understand format.
The old list format looked like:
['Item 1', [['Item 1.1', []], ['Item 1.2', []]]
And it is converted to:
['Item 1', ['Item 1.1', 'Item 1.2]]
"""
if not isinstance(list_, (tuple, list)) or len(list_) != 2:
return list_, False
first_item, second_item = list_
if second_item == []:
return [first_item], True
old_style_list = True
new_second_item = []
for sublist in second_item:
item, old_style_list = convert_old_style_list(sublist)
if not old_style_list:
break
new_second_item.extend(item)
if old_style_list:
second_item = new_second_item
return [first_item, second_item], old_style_list
def _helper(list_, tabs=1):
indent = u'\t' * tabs
output = []
list_length = len(list_)
i = 0
while i < list_length:
title = list_[i]
sublist = ''
sublist_item = None
if isinstance(title, (list, tuple)):
sublist_item = title
title = ''
elif i < list_length - 1:
next_item = list_[i+1]
if next_item and isinstance(next_item, (list, tuple)):
# The next item is a sub-list.
sublist_item = next_item
# We've processed the next item now too.
i += 1
if sublist_item:
sublist = _helper(sublist_item, tabs+1)
sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (indent, sublist,
indent, indent)
output.append('%s<li>%s%s</li>' % (indent,
escaper(force_unicode(title)), sublist))
i += 1
return '\n'.join(output)
value, converted = convert_old_style_list(value)
return mark_safe(_helper(value))
0
Example 34
Project: oioioi Source File: __init__.py
def tabbed_view(request, template, context, tabs, tab_kwargs, link_builder):
"""A framework for building pages that are split into tabs.
The current tab is picked using the 'key' GET parameter.
The given template is rendered using the given context, which is
extended by 'current_tab', representing the opened tab, 'tabs',
a set of 'obj' and 'link' pairs for each existing tab, where 'obj'
represents the tab and 'link' is a link to the tab's page,
and 'content', the tab's rendered content.
:param request: a HttpRequest object given to the view
:param template: the rendered template
:param context: additional context to be passed to the template
:param tabs: an iterable of tabs. Each tab must have a unique 'key'
attribute that will be used to create an URL to the tab,
a 'view' attribute returning either HttpResponseRedirect,
TemplateResponse or rendered html, and an optional 'condition'
attribute: a function taking a request and returning
if the tab should be accessible for this request. If there is
no condition then it is assumed to be always returning True.
:param tab_kwargs: a dict to be passed as kwargs to each tab's view
:param link_builder: a function which receives a tab and returns
a link to the tab. It should contain a proper path
and the appropriate 'key' parameter.
"""
tabs = [t for t in tabs if not hasattr(t, 'condition')
or t.condition(request)]
if 'key' not in request.GET:
if not tabs:
raise Http404
qs = request.GET.dict()
qs['key'] = next(iter(tabs)).key
return HttpResponseRedirect(request.path + '?' + urllib.urlencode(qs))
key = request.GET['key']
for tab in tabs:
if tab.key == key:
current_tab = tab
break
else:
raise Http404
response = current_tab.view(request, **tab_kwargs)
if isinstance(response, HttpResponseRedirect):
return response
if isinstance(response, TemplateResponse):
content = response.render().content
else:
content = response
tabs_context = [{'obj': tab, 'link': link_builder(tab)}
for tab in tabs]
context.update({
'current_tab': current_tab,
'tabs': tabs_context,
'content': mark_safe(force_unicode(content))
})
return TemplateResponse(request, template, context)
0
Example 35
Project: django-easymode Source File: fields.py
def __get__(self, obj, typ=None):
"""
Read the localised version of the field this descriptor emulates.
First try to see if the localised field is really set.
If not, then use ugettext_lazy to find a tranlation in the current language
for this field.
"""
# self must be returned in a getattr context.
if obj is None:
return self
current_language = translation.get_language()
real_field_name = get_real_fieldname(self.name, current_language)
vo = GettextVO()
# first check if the database contains the localized data
vo.stored_value = getattr(obj, real_field_name)
# the database does not have our localized data.
# check if we have a translation, first get the msgid, as a unicode string.
vo.msgid = get_localized_property(obj, self.name, getattr(settings, 'MSGID_LANGUAGE', settings.LANGUAGE_CODE))
# check the translation in the current language
# but avoid empty string and None
if valid_for_gettext(vo.msgid):
vo.msg = self.to_python(translation.ugettext(force_unicode(vo.msgid)))
elif valid_for_gettext(vo.stored_value):
# we can not use the msgid for gettext but we did find a valid
# translation in the database. Fine we stop here and return that
# value. No need for a standin, because we don't have a catalog value.
return vo.stored_value
else:
# we can not use the msgid for gettext lookups, so there is no
# point in trying. Check for fallback languages in database.
vo.fallback = get_localized_property(obj, self.name)
if not valid_for_gettext(vo.fallback):
# Also if we are sure we don't have any old
# translations in the catalog or something for the fallback
# languages in the database, we do not need to return a standin either
return vo.msgid
# we got here so we've got a valid messageid. Now collect data from the catalog(s)
# if there isn't anything new in the catalog belonging to the current language:
if vo.msg == vo.msgid:
# maybe we have a translation in any of the fallback languages.
if hasattr(settings, 'FALLBACK_LANGUAGES'):
# first check if the database has the localized data in
# any of the fallback languages.
vo.fallback = get_localized_property(obj, self.name)
# if the fallback is the same as the msgid, go and look in the catalog
if vo.fallback == vo.msgid:
# there might be a translation in any
# of the fallback languages.
for fallback in get_fallback_languages():
catalog = translation_catalogs(fallback)
msg = catalog.ugettext(force_unicode(vo.msgid))
if self.to_python(msg) != vo.msgid:
vo.fallback = self.to_python(msg)
break
elif vo.fallback:
# if a valid fallback is found, then, since the msg is equal
# to the msgid, the fallback is the winner.
vo.msg = vo.fallback
# if we came here we collected data from the catalog and we should return
# a standin. A standin is the return value, with some extra properties.
# see GettextVO for the extra properties added.
if valid_for_gettext(vo.stored_value):
vo.standin_value_is_from_database = True
# database always wins
return standin_for(vo.stored_value, **vo.__dict__)
elif valid_for_gettext(vo.msg):
# runner up is the translation in the native language
return standin_for(vo.msg, **vo.__dict__)
elif valid_for_gettext(vo.fallback):
# and last is the translation in a fallback language
return standin_for(vo.fallback, **vo.__dict__)
assert(valid_for_gettext(vo.msgid))
# there is a very very small probability that the translation of
# a valid msgid evaluates to empty string or None (after to_python).
# If that happened, we got here. I choose to return None, because i like
# to be like that
return None
0
Example 36
Project: django-dynamicforms Source File: views.py
def form_valid(self, form):
# save the result
data = DynamicFormData.objects.create(
dynamicform = self.dynamicform,
raw_post_data = self.request.raw_post_data,
headers = '\n'.join(
'%s: %s' % (h, self.request.META[h])
for h in HTTP_HEADERS if h in self.request.META
)
)
# create confirmation e-mail
if self.dynamicform.send_confirmation:
recipients_template = Template(self.dynamicform.email_recipients)
subject_template = Template(self.dynamicform.email_subject)
content_template = Template(self.dynamicform.email_content)
context = Context(form.cleaned_data)
recipients = recipients_template.render(context)
subject = subject_template.render(context)
content = content_template.render(context)
msg = EmailMultiAlternatives(
force_unicode(subject),
html2text(content),
settings.DEFAULT_FROM_EMAIL,
[address for name, address in rfc822.AddressList(recipients).addresslist],
)
msg.attach_alternative(content, "text/html")
msg.send()
# create e-mail for dynamicform manager
if self.dynamicform.notification_emails:
recipients = self.dynamicform.notification_emails.split(u',')
subject = _(u'Someone filled in your online form "%s"') % self.dynamicform.name
context = RequestContext(
self.request,
{
'form': form,
'dynamicform': self.dynamicform,
'dynamicformdata': data,
'site': Site.objects.get_current(),
},
)
content = render_to_string(self.dynamicform.email_template, context_instance=context)
msg = EmailMultiAlternatives(
force_unicode(subject),
html2text(content),
settings.SERVER_EMAIL,
[address for name, address in rfc822.AddressList(recipients).addresslist],
)
msg.attach_alternative(content, "text/html")
msg.send()
return super(ProcessDynamicFormView, self).form_valid(form)
0
Example 37
Project: django-easymode Source File: easy_copy_language.py
def handle(self, source, target, app=None, **options):
""" command execution """
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
models = get_models()
for model in models:
if hasattr(model, 'localized_fields'):
model_full_name = '%s.%s' % (model._meta.app_label, model._meta.module_name)
update_instances = set()
messages = []
for instance in model.objects.all():
for field in model.localized_fields:
source_field = get_real_fieldname(field, source)
target_field = get_real_fieldname(field, target)
if hasattr(instance, source_field) and hasattr(instance, target_field):
source_field_value = getattr(instance, source_field)
target_field_value = getattr(instance, target_field)
if target_field_value in (None, u'')\
and source_field_value not in (None, u''):
setattr(instance, target_field, force_unicode(source_field_value))
update_instances.add(instance)
messages.append(u"%s %s %s will become %s" % (model_full_name, instance, target_field, force_unicode(source_field_value)))
if len(update_instances):
if self.ask_for_confirmation(messages, u'%s.%s' % (model._meta.app_label, model._meta.module_name)):
for update_instance in update_instances:
print u"saving %s" % update_instance
update_instance.save()
0
Example 38
@filter_hook
def do_action(self, queryset):
# Check that the user has delete permission for the actual model
if not self.has_delete_permission():
raise PermissionDenied
using = router.db_for_write(self.model)
# Populate deletable_objects, a data structure of all related objects that
# will also be deleted.
deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
queryset, self.opts, self.user, self.admin_site, using)
# The user has already confirmed the deletion.
# Do the deletion and return a None to display the change list view again.
if self.request.POST.get('post'):
if perms_needed:
raise PermissionDenied
self.delete_models(queryset)
# Return None to display the change list page again.
return None
if len(queryset) == 1:
objects_name = force_unicode(self.opts.verbose_name)
else:
objects_name = force_unicode(self.opts.verbose_name_plural)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": objects_name}
else:
title = _("Are you sure?")
context = self.get_context()
context.update({
"title": title,
"objects_name": objects_name,
"deletable_objects": [deletable_objects],
'queryset': queryset,
"perms_lacking": perms_needed,
"protected": protected,
"opts": self.opts,
"app_label": self.app_label,
'action_checkbox_name': ACTION_CHECKBOX_NAME,
})
# Display the confirmation page
return TemplateResponse(self.request, self.delete_selected_confirmation_template or
self.get_template_list('views/model_delete_selected_confirm.html'), context, current_app=self.admin_site.name)
0
Example 39
Project: talk.org Source File: main.py
def change_stage(request, app_label, model_name, object_id):
model = models.get_model(app_label, model_name)
object_id = unquote(object_id)
if model is None:
raise Http404("App %r, model %r, not found" % (app_label, model_name))
opts = model._meta
if not request.user.has_perm(app_label + '.' + opts.get_change_permission()):
raise PermissionDenied
if request.POST and "_saveasnew" in request.POST:
return add_stage(request, app_label, model_name, form_url='../../add/')
try:
manipulator = model.ChangeManipulator(object_id)
except model.DoesNotExist:
raise Http404('%s object with primary key %r does not exist' % (model_name, escape(object_id)))
if request.POST:
new_data = request.POST.copy()
if opts.has_field_type(models.FileField):
new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data)
manipulator.do_html2python(new_data)
if not errors:
new_object = manipulator.save(new_data)
pk_value = new_object._get_pk_val()
# Construct the change message.
change_message = []
if manipulator.fields_added:
change_message.append(_('Added %s.') % get_text_list(manipulator.fields_added, _('and')))
if manipulator.fields_changed:
change_message.append(_('Changed %s.') % get_text_list(manipulator.fields_changed, _('and')))
if manipulator.fields_deleted:
change_message.append(_('Deleted %s.') % get_text_list(manipulator.fields_deleted, _('and')))
change_message = ' '.join(change_message)
if not change_message:
change_message = _('No fields changed.')
LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), CHANGE, change_message)
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)}
if "_continue" in request.POST:
request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
if '_popup' in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(new_object)})
return HttpResponseRedirect("../%s/" % pk_value)
elif "_addanother" in request.POST:
request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect("../add/")
else:
request.user.message_set.create(message=msg)
return HttpResponseRedirect("../")
else:
# Populate new_data with a "flattened" version of the current data.
new_data = manipulator.flatten_data()
# TODO: do this in flatten_data...
# If the object has ordered objects on its admin page, get the existing
# order and flatten it into a comma-separated list of IDs.
id_order_list = []
for rel_obj in opts.get_ordered_objects():
id_order_list.extend(getattr(manipulator.original_object, 'get_%s_order' % rel_obj.object_name.lower())())
if id_order_list:
new_data['order_'] = ','.join(map(str, id_order_list))
errors = {}
# Populate the FormWrapper.
form = oldforms.FormWrapper(manipulator, new_data, errors)
form.original = manipulator.original_object
form.order_objects = []
#TODO Should be done in flatten_data / FormWrapper construction
for related in opts.get_followed_related_objects():
wrt = related.opts.order_with_respect_to
if wrt and wrt.rel and wrt.rel.to == opts:
func = getattr(manipulator.original_object, 'get_%s_list' %
related.get_accessor_name())
orig_list = func()
form.order_objects.extend(orig_list)
c = template.RequestContext(request, {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'form': form,
'object_id': object_id,
'original': manipulator.original_object,
'is_popup': '_popup' in request.REQUEST,
})
return render_change_form(model, manipulator, c, change=True)
0
Example 40
Project: django-cms-search Source File: search_indexes.py
def page_index_factory(language_code):
class _PageIndex(_get_index_base()):
_language = language_code
language = indexes.CharField()
text = indexes.CharField(docuement=True, use_template=False)
pub_date = indexes.DateTimeField(model_attr='publication_date', null=True)
login_required = indexes.BooleanField(model_attr='login_required')
url = indexes.CharField(stored=True, indexed=False, model_attr='get_absolute_url')
title = indexes.CharField(stored=True, indexed=False, model_attr='get_title')
site_id = indexes.IntegerField(stored=True, indexed=True, model_attr='site_id')
def prepare(self, obj):
current_languge = get_language()
try:
if current_languge != self._language:
activate(self._language)
request = rf.get("/")
request.session = {}
request.LANGUAGE_CODE = self._language
self.prepared_data = super(_PageIndex, self).prepare(obj)
plugins = CMSPlugin.objects.filter(language=language_code, placeholder__in=obj.placeholders.all())
text = u''
for base_plugin in plugins:
instance, plugin_type = base_plugin.get_plugin_instance()
if instance is None:
# this is an empty plugin
continue
if hasattr(instance, 'search_fields'):
text += u' '.join(force_unicode(_strip_tags(getattr(instance, field, ''))) for field in instance.search_fields)
if getattr(instance, 'search_fulltext', False) or getattr(plugin_type, 'search_fulltext', False):
text += _strip_tags(instance.render_plugin(context=RequestContext(request))) + u' '
text += obj.get_meta_description() or u''
text += u' '
text += obj.get_meta_keywords() or u''
self.prepared_data['text'] = text
self.prepared_data['language'] = self._language
return self.prepared_data
finally:
if get_language() != current_languge:
activate(current_languge)
def index_queryset(self):
# get the correct language and exclude pages that have a redirect
base_qs = super(_PageIndex, self).index_queryset()
result_qs = EmptyQuerySet()
for site_obj in Site.objects.all():
qs = base_qs.published(site=site_obj.id).filter(
Q(title_set__language=language_code) & (Q(title_set__redirect__exact='') | Q(title_set__redirect__isnull=True)))
if 'publisher' in settings.INSTALLED_APPS:
qs = qs.filter(publisher_is_draft=True)
qs = qs.distinct()
result_qs |= qs
return result_qs
return _PageIndex
0
Example 41
Project: django-token-auth Source File: __init__.py
def testForwardToken(self):
client = Client()
# test forwarding of token
url = '/protected/'
token = Token(url=url)
token.save()
response = client.get(token.use_token())
self.failUnlessEqual(response.status_code, 302)
response = client.get(token.forward_token())
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(response.context['token'].can_forward, False)
self.failUnlessEqual(force_unicode(response.context['error']), 'Apologies! This token can not be forwarded.')
token.delete()
token = Token(url=url, forward_count=None)
token.save()
response = client.get(token.use_token())
self.failUnlessEqual(response.status_code, 302)
response = client.get(token.forward_token())
self.failUnlessEqual(response.context['token'].can_forward, True)
self.failUnlessEqual(force_unicode(response.context['error'], strings_only=True), None)
response = client.post(token.forward_token(), FORM_DATA_FORWARD_1)
self.failUnlessEqual(response.status_code, 302)
token.delete()
# test max number of forwards
url = '/protected/'
token = Token(url=url, forward_count=3)
token.save()
response = client.get(token.use_token())
response = client.get(token.forward_token())
self.failUnlessEqual(force_unicode(response.context['error'], strings_only=True), None)
response = client.post(token.forward_token(), FORM_DATA_FORWARD_1)
self.failUnlessEqual(response.status_code, 302)
# grab token from db
token = Token.objects.get(pk=token.pk)
self.failUnlessEqual(token.forward_count, 1)
response = client.post(token.forward_token(), FORM_DATA_FORWARD_1)
self.failUnlessEqual(response.status_code, 200)
# grab token from db
token = Token.objects.get(pk=token.pk)
self.failUnlessEqual(token.forward_count, 1)
response = client.post(token.forward_token(), FORM_DATA_FORWARD_2)
self.failUnlessEqual(response.status_code, 302)
# grab token from db
token = Token.objects.get(pk=token.pk)
self.failUnlessEqual(token.forward_count, 0)
0
Example 42
Project: django-markdown2 Source File: md2.py
def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Syntax::
{{ value|markdown2:"extension1_name,extension2_name..." }}
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
If the version of Markdown in use does not support extensions,
they will be silently ignored.
"""
try:
import markdown2
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in {% markdown %} filter: The python-markdown2 library isn't installed.")
return force_unicode(value)
else:
def parse_extra(extra):
if ':' not in extra:
return (extra, {})
name, values = extra.split(':', 1)
values = dict((str(val.strip()), True) for val in values.split('|'))
return (name.strip(), values)
extras = (e.strip() for e in arg.split(','))
extras = dict(parse_extra(e) for e in extras if e)
if 'safe' in extras:
del extras['safe']
safe_mode = True
else:
safe_mode = False
return mark_safe(markdown2.markdown(force_unicode(value), extras=extras, safe_mode=safe_mode))
0
Example 43
Project: scielo-manager Source File: helpers.py
def collect_new_values(form=None, formsets=None, as_json_string=False):
"""
Collect the "post save" data into a JSON-compatible structure.
returns something like this:
{
'form_data': {
'<field name 1>': <new field 1 value>,
'<field name 2>': <new field 2 value>,
...
},
formsets_data: [
# for each formset:
{
'added':[
{
'object_verbose_name': '<object verbose name>',
'object_unicode': '<object unicode>',
'<field name 1>': <new field 1 value>,
'<field name 2>': <new field 2 value>,
},
...
],
'changed': [
{
'object_verbose_name': '<object verbose name>',
'object_unicode': '<object unicode>',
'<field name X>': <new field X value>,
'<field name Y>': <new field Y value>,
'<field name Z>': <new field Z value>,
},
...
],
'deleted': [
{
'object_verbose_name': '<object verbose name>',
'object_unicode': '<object unicode>',
},
...
]
},
...
]
}
"""
result = {
"form_data": {},
"formsets_data": [],
}
if form:
for field_name in get_auditable_fields(form):
field_value = form.cleaned_data[field_name]
result["form_data"][field_name] = field_serializer(field_serializer(field_value))
if formsets:
for formset in formsets:
formset_data = {
'added': [],
'changed': [],
'deleted': [],
}
added_data = []
# formset NEW objects
for added_object in formset.new_objects:
object_values = {
'object_verbose_name': force_unicode(added_object._meta.verbose_name),
'object_unicode': force_unicode(added_object),
'fields': {}
}
for field in added_object._meta.local_fields:
field_name = field.get_attname()
field_value = getattr(added_object, field_name)
object_values['fields'][field_name] = field_serializer(field_value)
added_data.append(object_values)
formset_data['added'] = added_data
changed_data = []
# formset CHANGED objects
for changed_object, changed_fields in formset.changed_objects:
object_values = {
'object_verbose_name': force_unicode(changed_object._meta.verbose_name),
'object_unicode': force_unicode(changed_object),
'fields': {}
}
for field_name in changed_fields:
field_value = getattr(changed_object, field_name)
object_values['fields'][field_name] = field_serializer(field_value)
changed_data.append(object_values)
formset_data['changed'] = changed_data
deleted_data = []
# formset DELETED objects
for deleted_object in formset.deleted_objects:
object_values = {
'object_verbose_name': force_unicode(deleted_object._meta.verbose_name),
'object_unicode': force_unicode(deleted_object),
}
deleted_data.append(object_values)
formset_data['deleted'] = deleted_data
# save formset data in the results, if any
if any([added_data, changed_data, deleted_data]):
result["formsets_data"].append(formset_data)
if as_json_string:
return json.dumps(result)
else:
return result
0
Example 44
Project: DistrictBuilder Source File: admin.py
def delete_selected_subject(modeladmin, request, queryset):
"""
This is invoked from the dropdown menu in the admin as a bulk action.
This overrides the
"""
opts = modeladmin.model._meta
app_label = opts.app_label
# Check that the user has delete permission for the actual model
# BUT we can't use modeladmin.has_delete_permission, as it's overridden
# above to hide the delete button on the change form.
if not request.user.has_perm(modeladmin.opts.app_label + '.' + modeladmin.opts.get_delete_permission()):
raise PermissionDenied
if request.POST.get('post'):
n = queryset.count()
if n:
engine = inflect.engine()
for obj in queryset:
obj_display = force_unicode(obj)
modeladmin.log_deletion(request, obj, obj_display)
queryset.delete()
modeladmin.message_user(request, _('Successfully deleted %(count)d %(item)s') % {
'count': n,
'item': engine.plural('subject', n)
})
# Return None to display the change list page again.
return None
warned = 'warned' in request.REQUEST and request.REQUEST['warned'] == 'on'
context = {
"object_name": force_unicode(opts.verbose_name),
"deletable_objects": queryset.all(),
"queryset": queryset,
"opts": opts,
"app_label": app_label,
"action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
"warned": warned
}
# Display the confirmation page
return render_to_response("admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
context, context_instance=template.RequestContext(request))
0
Example 45
Project: scielo-manager Source File: tests_helpers.py
def test_POST_valid_formdata_do_log(self):
# with:
perm_journal_change = _makePermission(perm='change_journal', model='journal', app_label='journalmanager')
perm_journal_list = _makePermission(perm='list_journal', model='journal', app_label='journalmanager')
self.user.user_permissions.add(perm_journal_change)
self.user.user_permissions.add(perm_journal_list)
sponsor = jm_modelfactories.SponsorFactory.create()
use_license = jm_modelfactories.UseLicenseFactory.create()
language = jm_modelfactories.LanguageFactory.create()
subject_category = jm_modelfactories.SubjectCategoryFactory.create()
study_area = jm_modelfactories.StudyAreaFactory.create()
form = self.app.get(reverse('journal.add'), user=self.user).forms['journal-form']
form['journal-sponsor'] = [sponsor.pk]
form['journal-study_areas'] = [study_area.pk]
form['journal-ctrl_vocabulary'] = 'decs'
form['journal-frequency'] = 'Q'
form['journal-final_num'] = ''
form['journal-eletronic_issn'] = '0102-6720'
form['journal-init_vol'] = '1'
form['journal-title'] = u'ABCD. Arquivos Brasileiros de Cirurgia Digestiva (São Paulo)'
form['journal-title_iso'] = u'ABCD. Arquivos B. de C. D. (São Paulo)'
form['journal-short_title'] = u'ABCD.(São Paulo)'
form['journal-editorial_standard'] = 'vancouv'
form['journal-scielo_issn'] = 'print'
form['journal-init_year'] = '1986'
form['journal-acronym'] = 'ABCD'
form['journal-pub_level'] = 'CT'
form['journal-init_num'] = '1'
form['journal-final_vol'] = ''
form['journal-subject_descriptors'] = 'MEDICINA, CIRURGIA, GASTROENTEROLOGIA, GASTROENTEROLOGIA'
form['journal-print_issn'] = '0102-6720'
form['journal-copyrighter'] = 'Texto do copyrighter'
form['journal-publisher_name'] = 'Colégio Brasileiro de Cirurgia Digestiva'
form['journal-publisher_country'] = 'BR'
form['journal-publisher_state'] = 'SP'
form['journal-publication_city'] = 'São Paulo'
form['journal-editor_name'] = 'Colégio Brasileiro de Cirurgia Digestiva'
form['journal-editor_address'] = 'Av. Brigadeiro Luiz Antonio, 278 - 6° - Salas 10 e 11'
form['journal-editor_address_city'] = 'São Paulo'
form['journal-editor_address_state'] = 'SP'
form['journal-editor_address_zip'] = '01318-901'
form['journal-editor_address_country'] = 'BR'
form['journal-editor_phone1'] = '(11) 3288-8174'
form['journal-editor_phone2'] = '(11) 3289-0741'
form['journal-editor_email'] = '[email protected]'
form['journal-use_license'] = use_license.pk
form['journal-languages'] = [language.pk]
form['journal-abstract_keyword_languages'] = [language.pk]
form.set('journal-subject_categories', [str(subject_category.pk),])
form['journal-is_indexed_scie'] = True
form['journal-is_indexed_ssci'] = False
form['journal-is_indexed_aehci'] = True
# when:
response = form.submit().follow()
# then:
self.assertIn('Saved.', response.body)
self.assertIn('ABCD.(São Paulo)', response.body)
self.assertTemplateUsed(response, 'journalmanager/journal_dash.html')
self.assertEqual(audit_models.AuditLogEntry.objects.count(), 1)
log_entry = audit_models.AuditLogEntry.objects.all()[0]
audited_object = log_entry.get_audited_object()
# inspect audited log entry data:
self.assertEqual(log_entry.action_flag, audit_models.ADDITION)
self.assertEqual(log_entry.object_id, unicode(audited_object.pk))
self.assertEqual(log_entry.content_type, ContentType.objects.get_for_model(audited_object))
self.assertEqual(log_entry.old_values, None)
self.assertEqual(log_entry.user, self.user)
fields_edited = [
'sponsor',
'use_license',
'languages',
'abstract_keyword_languages',
'subject_categories',
'study_areas',
'title',
'title_iso',
'short_title',
'acronym',
'scielo_issn',
'print_issn',
'eletronic_issn',
'subject_descriptors',
'init_year',
'init_vol',
'init_num',
'frequency',
'editorial_standard',
'ctrl_vocabulary',
'pub_level',
'copyrighter',
'editor_name',
'editor_address',
'editor_address_city',
'editor_address_state',
'editor_address_zip',
'editor_address_country',
'editor_phone1',
'editor_phone2',
'editor_email',
'publisher_name',
'publisher_country',
'publisher_state',
'publication_city',
'is_indexed_scie',
'is_indexed_aehci',
]
self.assertEqual(log_entry.new_values.keys(), [u'form_data', u'formsets_data'])
for field_edited in fields_edited:
# all edited fields are in "new_values"-dict
self.assertIn(field_edited, log_entry.new_values['form_data'].keys())
# all edited fields are in the "change message" field
self.assertIn(field_edited, log_entry.change_message)
# compare form data and stored new_values data
for k,v in log_entry.new_values['form_data'].iteritems():
form_value = form['journal-%s' % k].value
self.assertEqual(log_entry.new_values['form_data'][k], force_unicode(v))
0
Example 46
Project: coursys Source File: util.py
def html_output_alt(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row,
extra_css_class_attr = "manual_css_classes"):
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
output, hidden_fields = [], []
for name, field in self.fields.items():
html_class_attr = ''
bf = BoundField(self, field, name)
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
if bf.is_hidden:
if bf_errors:
top_errors.extend([u'(Hidden field %s) extra_css_class_attr%s' % (name, force_unicode(e)) for e in bf_errors])
hidden_fields.append(unicode(bf))
else:
# Create a 'class="..."' atribute if the row should have any
# CSS classes applied.
css_classes = bf.css_classes(getattr(field, extra_css_class_attr, None))
if css_classes:
html_class_attr = ' class="%s"' % css_classes
if errors_on_separate_row and bf_errors:
output.append(error_row % force_unicode(bf_errors))
if bf.label:
label = conditional_escape(force_unicode(bf.label))
# Only add the suffix if the label does not end in
# punctuation.
if self.label_suffix:
if label[-1] not in ':?.!':
label += self.label_suffix
label = bf.label_tag(label) or ''
else:
label = ''
if field.help_text:
help_text = help_text_html % force_unicode(field.help_text)
else:
help_text = u''
output.append(normal_row % {
'errors': force_unicode(bf_errors),
'label': force_unicode(label),
'field': unicode(bf),
'help_text': help_text,
'html_class_attr': html_class_attr
})
#if top_errors:
# output.insert(0, error_row % force_unicode(top_errors))
if hidden_fields: # Insert any hidden fields in the last row.
str_hidden = u''.join(hidden_fields)
if output:
last_row = output[-1]
# Chop off the trailing row_ender (e.g. '</td></tr>') and
# insert the hidden fields.
if not last_row.endswith(row_ender):
# This can happen in the as_p() case (and possibly others
# that users write): if there are only top errors, we may
# not be able to conscript the last row for our purposes,
# so insert a new, empty row.
last_row = (normal_row % {'errors': '', 'label': '',
'field': '', 'help_text':'',
'html_class_attr': html_class_attr})
output.append(last_row)
output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
else:
# If there aren't any rows in the output, just append the
# hidden fields.
output.append(str_hidden)
return mark_safe(u'\n'.join(output))
0
Example 47
Project: talk.org Source File: admin_list.py
def items_for_result(cl, result):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.lookup_opts.admin.list_display:
row_class = ''
try:
f = cl.lookup_opts.get_field(field_name)
except models.FieldDoesNotExist:
# For non-field list_display values, the value is either a method
# or a property.
try:
attr = getattr(result, field_name)
allow_tags = getattr(attr, 'allow_tags', False)
boolean = getattr(attr, 'boolean', False)
if callable(attr):
attr = attr()
if boolean:
allow_tags = True
result_repr = _boolean_icon(attr)
else:
result_repr = smart_unicode(attr)
except (AttributeError, ObjectDoesNotExist):
result_repr = EMPTY_CHANGELIST_VALUE
else:
# Strip HTML tags in the resulting text, except if the
# function has an "allow_tags" attribute set to True.
if not allow_tags:
result_repr = escape(result_repr)
else:
result_repr = mark_safe(result_repr)
else:
field_val = getattr(result, f.attname)
if isinstance(f.rel, models.ManyToOneRel):
if field_val is not None:
result_repr = escape(getattr(result, f.name))
else:
result_repr = EMPTY_CHANGELIST_VALUE
# Dates and times are special: They're formatted in a certain way.
elif isinstance(f, models.DateField) or isinstance(f, models.TimeField):
if field_val:
(date_format, datetime_format, time_format) = get_date_formats()
if isinstance(f, models.DateTimeField):
result_repr = capfirst(dateformat.format(field_val, datetime_format))
elif isinstance(f, models.TimeField):
result_repr = capfirst(dateformat.time_format(field_val, time_format))
else:
result_repr = capfirst(dateformat.format(field_val, date_format))
else:
result_repr = EMPTY_CHANGELIST_VALUE
row_class = ' class="nowrap"'
# Booleans are special: We use images.
elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
result_repr = _boolean_icon(field_val)
# DecimalFields are special: Zero-pad the decimals.
elif isinstance(f, models.DecimalField):
if field_val is not None:
result_repr = ('%%.%sf' % f.decimal_places) % field_val
else:
result_repr = EMPTY_CHANGELIST_VALUE
# Fields with choices are special: Use the representation
# of the choice.
elif f.choices:
result_repr = dict(f.choices).get(field_val, EMPTY_CHANGELIST_VALUE)
else:
result_repr = escape(field_val)
if force_unicode(result_repr) == '':
result_repr = mark_safe(' ')
# If list_display_links not defined, add the link tag to the first field
if (first and not cl.lookup_opts.admin.list_display_links) or field_name in cl.lookup_opts.admin.list_display_links:
table_tag = {True:'th', False:'td'}[first]
first = False
url = cl.url_for_result(result)
# Convert the pk to something that can be used in Javascript.
# Problem cases are long ints (23L) and non-ASCII strings.
result_id = repr(force_unicode(getattr(result, pk)))[1:]
yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \
(table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
else:
yield mark_safe(u'<td%s>%s</td>' % (row_class, conditional_escape(result_repr)))
0
Example 48
Project: talk.org Source File: main.py
def _get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current_depth):
"Helper function that recursively populates deleted_objects."
nh = _nest_help # Bind to local variable for performance
if current_depth > 16:
return # Avoid recursing too deep.
opts_seen = []
for related in opts.get_all_related_objects():
if related.opts in opts_seen:
continue
opts_seen.append(related.opts)
rel_opts_name = related.get_accessor_name()
if isinstance(related.field.rel, models.OneToOneRel):
try:
sub_obj = getattr(obj, rel_opts_name)
except ObjectDoesNotExist:
pass
else:
if related.opts.admin:
p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission())
if not user.has_perm(p):
perms_needed.add(related.opts.verbose_name)
# We don't care about populating deleted_objects now.
continue
if related.field.rel.edit_inline or not related.opts.admin:
# Don't display link to edit, because it either has no
# admin or is edited inline.
nh(deleted_objects, current_depth, [mark_safe(u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), sub_obj)), []])
else:
# Display a link to the admin page.
nh(deleted_objects, current_depth, [mark_safe(u'%s: <a href="../../../../%s/%s/%s/">%s</a>' %
(escape(force_unicode(capfirst(related.opts.verbose_name))),
related.opts.app_label,
related.opts.object_name.lower(),
sub_obj._get_pk_val(), sub_obj)), []])
_get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2)
else:
has_related_objs = False
for sub_obj in getattr(obj, rel_opts_name).all():
has_related_objs = True
if related.field.rel.edit_inline or not related.opts.admin:
# Don't display link to edit, because it either has no
# admin or is edited inline.
nh(deleted_objects, current_depth, [u'%s: %s' % (force_unicode(capfirst(related.opts.verbose_name)), escape(sub_obj)), []])
else:
# Display a link to the admin page.
nh(deleted_objects, current_depth, [mark_safe(u'%s: <a href="../../../../%s/%s/%s/">%s</a>' % \
(escape(force_unicode(capfirst(related.opts.verbose_name))), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(sub_obj))), []])
_get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2)
# If there were related objects, and the user doesn't have
# permission to delete them, add the missing perm to perms_needed.
if related.opts.admin and has_related_objs:
p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission())
if not user.has_perm(p):
perms_needed.add(related.opts.verbose_name)
for related in opts.get_all_related_many_to_many_objects():
if related.opts in opts_seen:
continue
opts_seen.append(related.opts)
rel_opts_name = related.get_accessor_name()
has_related_objs = False
# related.get_accessor_name() could return None for symmetrical relationships
if rel_opts_name:
rel_objs = getattr(obj, rel_opts_name, None)
if rel_objs:
has_related_objs = True
if has_related_objs:
for sub_obj in rel_objs.all():
if related.field.rel.edit_inline or not related.opts.admin:
# Don't display link to edit, because it either has no
# admin or is edited inline.
nh(deleted_objects, current_depth, [_('One or more %(fieldname)s in %(name)s: %(obj)s') % \
{'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name), 'obj': escape(sub_obj)}, []])
else:
# Display a link to the admin page.
nh(deleted_objects, current_depth, [
mark_safe((_('One or more %(fieldname)s in %(name)s:') % {'fieldname': escape(force_unicode(related.field.verbose_name)), 'name': escape(force_unicode(related.opts.verbose_name))}) + \
(u' <a href="../../../../%s/%s/%s/">%s</a>' % \
(related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(sub_obj)))), []])
# If there were related objects, and the user doesn't have
# permission to change them, add the missing perm to perms_needed.
if related.opts.admin and has_related_objs:
p = u'%s.%s' % (related.opts.app_label, related.opts.get_change_permission())
if not user.has_perm(p):
perms_needed.add(related.opts.verbose_name)
0
Example 49
Project: redsolution-cms Source File: admin.py
def change_view(self, request, **kwargs):
"The 'change' admin view for this model"
model = self.model
opts = model._meta
try:
obj = self.model.objects.get_settings()
except model.DoesNotExist:
# Don't raise Http404 just yet, because we haven't checked
# permissions yet. We don't want an unauthenticated user to be able
# to determine whether a given object exists.
obj = None
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(kwargs.get('object_id', ''))})
if request.method == 'POST' and request.POST.has_key("_saveasnew"):
return self.add_view(request, form_url='../add/')
ModelForm = self.get_form(request, obj)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet in self.get_formsets(request, new_object):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix)
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=True)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=True)
self.construct_change_message(request, form, formsets)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet in self.get_formsets(request, obj):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix)
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'original': obj,
'is_popup': request.REQUEST.has_key('_popup'),
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
return self.render_change_form(request, context, change=True, obj=obj)
0
Example 50
Project: bugle_project Source File: typogrify.py
def caps(text):
"""Wraps multiple capital letters in ``<span class="caps">``
so they can be styled with CSS.
>>> caps("A message from KU")
u'A message from <span class="caps">KU</span>'
Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't.
>>> caps("<PRE>CAPS</pre> more CAPS")
u'<PRE>CAPS</pre> more <span class="caps">CAPS</span>'
>>> caps("A message from 2KU2 with digits")
u'A message from <span class="caps">2KU2</span> with digits'
>>> caps("Dotted caps followed by spaces should never include them in the wrap D.O.T. like so.")
u'Dotted caps followed by spaces should never include them in the wrap <span class="caps">D.O.T.</span> like so.'
All caps with with apostrophes in them shouldn't break. Only handles dump apostrophes though.
>>> caps("JIMMY'S")
u'<span class="caps">JIMMY\\'S</span>'
>>> caps("<i>D.O.T.</i>HE34T<b>RFID</b>")
u'<i><span class="caps">D.O.T.</span></i><span class="caps">HE34T</span><b><span class="caps">RFID</span></b>'
"""
text = force_unicode(text)
try:
import smartypants
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% caps %} filter: The Python SmartyPants library isn't installed."
return text
tokens = smartypants._tokenize(text)
result = []
in_skipped_tag = False
cap_finder = re.compile(r"""(
(\b[A-Z\d]* # Group 2: Any amount of caps and digits
[A-Z]\d*[A-Z] # A cap string much at least include two caps (but they can have digits between them)
[A-Z\d']*\b) # Any amount of caps and digits or dumb apostsrophes
| (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space
(?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more
(?:\s|\b|$))
""", re.VERBOSE)
def _cap_wrapper(matchobj):
"""This is necessary to keep dotted cap strings to pick up extra spaces"""
if matchobj.group(2):
return """<span class="caps">%s</span>""" % matchobj.group(2)
else:
if matchobj.group(3)[-1] == " ":
caps = matchobj.group(3)[:-1]
tail = ' '
else:
caps = matchobj.group(3)
tail = ''
return """<span class="caps">%s</span>%s""" % (caps, tail)
tags_to_skip_regex = re.compile("<(/)?(?:pre|code|kbd|script|math)[^>]*>", re.IGNORECASE)
for token in tokens:
if token[0] == "tag":
# Don't mess with tags.
result.append(token[1])
close_match = tags_to_skip_regex.match(token[1])
if close_match and close_match.group(1) == None:
in_skipped_tag = True
else:
in_skipped_tag = False
else:
if in_skipped_tag:
result.append(token[1])
else:
result.append(cap_finder.sub(_cap_wrapper, token[1]))
output = "".join(result)
return mark_safe(output)