我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.html.escape()。
def make_subscription_update_notification(new=None, removed=None): bits = ['The project subscriptions for this room were updated. '] def _proj(project): return '<strong>%s</strong>' % escape(project.name) if new: if len(new) == 1: bits.append('New project: %s. ' % _proj(new[0])) else: bits.append('New projects: %s. ' % ', '.join(_proj(x) for x in new)) if removed: if len(removed) == 1: bits.append('Removed project: %s' % _proj(removed[0])) else: bits.append('Removed projects: %s' % ', '.join(_proj(x) for x in removed)) return { 'message': ' '.join(bits).strip(), 'color': 'green', 'notify': False, }
def find_books(request): """ Generates list with books of data which user entered. At first it check full equality in name, after tries to check if contains some part of entered data. """ if request.is_ajax(): search_book_form = SearchBookForm(request.GET) if search_book_form.is_valid(): search_data = search_book_form.cleaned_data['data'] filtered_books = Book.exclude_private_books(request.user, Book.fetch_books(search_data)) books = Book.generate_books(filtered_books) for book in books: book['name'] = escape(book['name']) book['author'] = escape(book['author']) return HttpResponse(json.dumps(books), content_type='application/json') else: return HttpResponse(status=404)
def generate_authors(request): """ Returns a list of authors. """ if request.is_ajax(): authors_form = GenerateAuthorsForm(request.GET) if authors_form.is_valid(): list_of_authors = [escape(author) for author in Author.get_authors_list(authors_form.cleaned_data['part'])] return HttpResponse(json.dumps(list_of_authors), content_type='application/json') else: return HttpResponse(status=404) # ----------------------------------------------------------------------------------------------------------------------
def get_attachment_name(request, attachment): server_id = attachment.get("server_id", None) if "instance" in attachment and attachment['instance']: name = attachment["instance"].name else: try: server = api.nova.server_get(request, server_id) name = server.name except Exception: name = None exceptions.handle(request, _("Unable to retrieve " "attachment information.")) try: url = reverse("horizon:project:instances:detail", args=(server_id,)) instance = '<a href="%s">%s</a>' % (url, html.escape(name)) except NoReverseMatch: instance = html.escape(name) return instance
def test_stack_output(self): self.assertEqual(u'<pre>foo</pre>', mappings.stack_output('foo')) self.assertEqual(u'', mappings.stack_output(None)) outputs = ['one', 'two', 'three'] # On Python 3, the pretty JSON output doesn't add space before newline if six.PY3: expected_text = """[\n "one",\n "two",\n "three"\n]""" else: expected_text = """[\n "one", \n "two", \n "three"\n]""" self.assertEqual(u'<pre>%s</pre>' % html.escape(expected_text), mappings.stack_output(outputs)) outputs = {'foo': 'bar'} expected_text = """{\n "foo": "bar"\n}""" self.assertEqual(u'<pre>%s</pre>' % html.escape(expected_text), mappings.stack_output(outputs)) self.assertEqual( u'<a href="http://www.example.com/foo" target="_blank">' 'http://www.example.com/foo</a>', mappings.stack_output('http://www.example.com/foo'))
def render_option(self, selected_choices, option_value, option_label): option_value = force_text(option_value) other_html = (u' selected="selected"' if option_value in selected_choices else '') if callable(self.transform_html_attrs): html_attrs = self.transform_html_attrs(option_label) other_html += flatatt(html_attrs) if not isinstance(option_label, (six.string_types, Promise)): for data_attr in self.data_attrs: data_value = html.conditional_escape( force_text(getattr(option_label, data_attr, ""))) other_html += ' data-%s="%s"' % (data_attr, data_value) if callable(self.transform): option_label = self.transform(option_label) return u'<option value="%s"%s>%s</option>' % ( html.escape(option_value), other_html, html.conditional_escape(force_text(option_label)))
def _format_callback(self, obj, user, admin_site, perms_needed): has_admin = obj.__class__ in admin_site._registry opts = obj._meta if has_admin: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) p = get_delete_permission(opts) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe('%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return '%s: %s' % (capfirst(opts.verbose_name), force_text(obj))
def label_for_value(self, value): rel_to = self.rel.to key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) related_url = reverse('admin:%s_%s_change' % (rel_to._meta.app_label, rel_to._meta.model_name), args=(value, ), current_app=self.admin_site.name) edit_str = ' <a href="%s" title="View" target="_blank">View %s</a>' % (related_url, rel_to._meta.model_name) return ' <strong>%s</strong>%s' % ( escape(Truncator(obj).words(14, truncate='...')), edit_str ) except (ValueError, self.rel.to.DoesNotExist): return ''
def has_delete_permission(self, request, obj=None): return False # def object_link(self, obj): # if obj.action_flag == DELETION: # link = escape(obj.object_repr) # else: # ct = obj.content_type # link = u'<a href="%s">%s</a>' % ( # reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]), # escape(obj.object_repr), # ) # return link # object_link.allow_tags = True # object_link.admin_order_field = 'object_repr' # object_link.short_description = u'object'
def wikilink(value): """ Produce wiki style links to other pages within the database, for use in comments fields: {{ a_note|wikilink|truncatewords_html:5 }} Note that it's better to use truncatewords_html with this filter, rather than plain truncatewords """ WIKILINK_RE = re.compile(r""" (?P<lead>\s|^) # possible leading whitespace (?P<wikilink>/ # an initial / (\w+/)+ # multiples of any number of identifier chars + / ) """, re.VERBOSE) def wikilink_sub_callback(match_obj): link = match_obj.group("wikilink") lead = match_obj.group("lead") return '%s<a href="%s">%s</a>' % (lead, escape(link), escape(link)) return mark_safe(WIKILINK_RE.sub(wikilink_sub_callback, value))
def fixedwidth(field, name=None, pt=6, width=16, maxlen=64, pretty=False): """Render a field with a fixed width.""" @display_field(name or field, field) def f(task): val = getattr(task, field) if pretty: val = pformat(val, width=width) if val.startswith("u'") or val.startswith('u"'): val = val[2:-1] shortval = val.replace(',', ',\n') shortval = shortval.replace('\n', '|br/|') if len(shortval) > maxlen: shortval = shortval[:maxlen] + '...' styled = FIXEDWIDTH_STYLE.format( escape(val[:255]), pt, escape(shortval), ) return styled.replace('|br/|', '<br/>') return f
def optional_logout(request, user): """ Include a logout snippet if REST framework's logout view is in the URLconf. """ try: logout_url = reverse('rest_framework:logout') except NoReverseMatch: snippet = format_html('<li class="navbar-text">{user}</li>', user=escape(user)) return mark_safe(snippet) snippet = """<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> {user} <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href='{href}?next={next}'>Log out</a></li> </ul> </li>""" snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path)) return mark_safe(snippet)
def render(self, name, value, attrs=None): """ Renders custom widget with the image preview for uploaded images or the default widget if the image has not yet been uploaded. """ # if the image is uploaded, the 'image' argument # is an instance of GalleryImageFieldFile if isinstance(value, fields.GalleryImageFieldFile): # get image data data = utils.create_image_data(value) # fill the template and replace the default one self.template_with_initial = self.template.format( settings.CONF['preview_width'] + 14, settings.CONF['preview_height'] + 14, settings.CONF['preview_width'], settings.CONF['preview_height'], settings.CONF['preview_height'], html.escape(json.dumps(data)), utils.create_static_url("content_gallery/img/zoom.png"), settings.CONF['preview_width'] - 55 ) # render the widget return super().render(name, value, attrs)
def gallery_image_data(obj): """ Returns data of the image related to the object. Used to construct previews. """ # get the first image related to the object image = utils.get_first_image(obj) try: # get data related to the object if the image exists data = { 'app_label': image.content_type.app_label, 'content_type': image.content_type.model, 'object_id': str(image.object_id) } except AttributeError: # set empty data if the image does not exist data = {} # return the image and data in JSON format data_json = json.dumps(data) return { 'image': image, 'data_image': html.escape(data_json) }
def get_default_address(self): address_data = { "street": self.properties.get("addr:street"), "housenumber": self.properties.get("addr:housenumber"), "city": self.properties.get("addr:city"), "postcode": self.properties.get("addr:postcode") } if all(address_data.values()): return _("Adresse exacte : {housenumber} {street}, {postcode} {city}").format( housenumber=escape(address_data["housenumber"]), street=escape(address_data["street"]), postcode=escape(address_data["postcode"]), city=escape(address_data["city"]) ) elif address_data["housenumber"] and address_data["street"]: return _("Adresse exacte : {housenumber}, {street}").format( housenumber=escape(address_data["housenumber"]), street=escape(address_data["street"]) ) else: return ''
def post(self, request): config = ContactsConfig.get_solo() form = ContactForm(request.POST, request.FILES) if form.is_valid(): message = form.save(commit=False) referer = request.POST.get('referer', request.build_absolute_uri(request.path_info)) message.referer = escape(referer) message.save() receivers = NotificationReceiver.objects.all().values_list('email', flat=True) send_template(request, receivers, subject=_('Message from {domain}'), template='contacts/mails/message.html', context={ 'message': message, } ) return redirect('contacts:index') else: return self.render_to_response({ 'config': config, 'addresses': Address.objects.first(), 'form': form, })
def __iter__(self): """ ????????? XML """ yield """<?xml version="1.0" encoding="utf-8"?><sphinx:docset xmlns:sphinx="http://sphinxsearch.com/">""" yield from self.scheme for instance in self.get_queryset(): docuemnt = self.build_document(instance) try: document = self.scheme.format(docuemnt, doc_id=instance.id) except ValidationError as e: logger.error(e.message) return else: output = """<sphinx:document id="{0}">""".format(instance.id) for key, value in document.items(): output += """<{0}>{1}</{0}>""".format( key, escape(value) or '' ) output += """</sphinx:document>""" yield output yield """</sphinx:docset>"""
def add_item_elements(self, handler, item): super(ItunesFeed, self).add_item_elements(handler, item) handler.addQuickElement('itunes:episodeType', item['itunes']['type']) handler.addQuickElement('itunes:title', item['itunes']['title']) handler.addQuickElement('itunes:summary', item['itunes']['summary']) handler.addQuickElement('content:encoded', item['itunes']['notes'], escape=False, cdata=True) handler.addQuickElement('itunes:author', item['itunes']['author']['name']) handler.addQuickElement('itunes:image', '', {'href': item['itunes']['image']}) handler.addQuickElement('itunes:explicit', item['itunes']['explicit']) handler.addQuickElement('itunes:block', item['itunes']['block']) handler.addQuickElement('itunes:isClosedCaptioned', item['itunes']['cc']) if item['itunes']['season']: handler.addQuickElement('itunes:season', item['itunes']['season']) if item['itunes']['number']: handler.addQuickElement('itunes:episode', item['itunes']['number']) if item['itunes']['duration']: handler.addQuickElement('itunes:duration', item['itunes']['duration'])
def test_view_product(self): """ test product view loads """ product = Product.active.all()[0] product_url = product.get_absolute_url() url_entry = urlresolvers.resolve(product_url) template_name = url_entry[2]['template_name'] response = self.client.get(product_url) self.failUnless(response) self.assertEqual(response.status_code, httplib.OK) self.assertTemplateUsed(response, template_name) self.assertContains(response, product.name) self.assertContains(response, html.escape(product.description)) # check for cart form in product page response cart_form = response.context[0]['form'] self.failUnless(cart_form) # check that the cart form is instance of correct form class self.failUnless(isinstance(cart_form, ProductAddToCartForm)) product_reviews = response.context[0].get('product_reviews',None) self.failIfEqual(product_reviews, None)
def html(self, plain=False): old = '\n'.join(sorted(str(countries.name(c)) for c in self.old)) new = '\n'.join(sorted(str(countries.name(c)) for c in self.new)) dmp = diff_match_patch() a, b, lineArray = dmp.diff_linesToChars(old, new) diff = dmp.diff_main(a, b, checklines=False) dmp.diff_cleanupSemantic(diff) dmp.diff_charsToLines(diff, lineArray) result = [] for op, country in diff: if op: result.append('<div class="{}">{}</div>'.format( 'inserted' if op > 0 else 'deleted', escape(country))) else: result.append('<div>{}</div>'.format(escape(country))) return '\n'.join(result)
def get_results_from_search_response(response): parsed = response.json() formatted_results = [] for result in parsed['hits']['hits']: formatted = format_company_details(result['_source']) if 'highlight' in result: highlighted = '...'.join( result['highlight'].get('description', '') or result['highlight'].get('summary', '') ) # escape all html tags other than <em> and </em> highlighted_escaped = ( escape(highlighted) .replace('<em>', '<em>') .replace('</em>', '</em>') ) formatted['highlight'] = mark_safe(highlighted_escaped) formatted_results.append(formatted) parsed['results'] = formatted_results return parsed
def dict_for_view(self, user, through=None): if not through: through = self.id humanized_timestamp = "%s (edited)" % self.humanized_timestamp if self.edited else self.humanized_timestamp is_author = bool(user.is_authenticated and self.author == user.profile) is_following_author = bool(user.is_authenticated and self.author_id in user.profile.following_ids) profile_id = user.profile.id if getattr(user, "profile", None) else "" return { "author": self.author_id, "author_guid": self.author.guid, "author_handle": self.author.handle, "author_home_url": self.author.home_url, "author_image": self.author.safer_image_url_small, "author_is_local": self.local, "author_name": escape(self.author.name) or self.author.handle, "author_profile_url": self.author.get_absolute_url(), "reply_count": self.reply_count, "content_type": self.content_type.string_value, "delete_url": reverse("content:delete", kwargs={"pk": self.id}) if is_author else "", "detail_url": self.get_absolute_url(), "formatted_timestamp": self.timestamp, "guid": self.guid, "has_shared": Content.has_shared(self.id, profile_id) if profile_id else False, "humanized_timestamp": humanized_timestamp, "id": self.id, "is_authenticated": bool(user.is_authenticated), "is_author": is_author, "is_following_author": is_following_author, "parent": self.parent_id if self.content_type == ContentType.REPLY else "", "profile_id": profile_id, "rendered": self.rendered, "reply_url": reverse("content:reply", kwargs={"pk": self.id}) if user.is_authenticated else "", "shares_count": self.shares_count, "slug": self.slug, "through": through, "update_url": reverse("content:update", kwargs={"pk": self.id}) if is_author else "", }
def _format_user(user): if user is None: name = 'system' elif user.name: name = user.name else: parts = user.username.split('@') if len(parts) == 1: name = user.username else: name = parts[0].lower() return '<em>%s</em>' % escape(name)
def make_event_notification(group, event, tenant, new=True, event_target=False): project = event.project level = group.get_level_display().upper() link = group.get_absolute_url() if event_target: link = '%s/events/%s/' % (link.rstrip('/'), event.id) color = COLORS.get(level, 'purple') # Legacy message message = ('[%(level)s]%(project_name)s %(message)s ' '[<a href="%(link)s">view</a>]') % { 'level': escape(level), 'project_name': '<strong>%s</strong>' % escape(project.name), 'message': escape(event.error()), 'link': escape(link), } return { 'color': color, 'message': message, 'format': 'html', 'card': _make_event_card(group, event, new=new, event_target=event_target), 'notify': True, }
def make_generic_notification(text, color=None, notify=False): return { 'message': escape(text), 'color': color, 'notify': notify, }
def sort(request): """ Returns data sorted data depending on criterion. """ if request.is_ajax(): sort_form = SortForm(request.GET) if sort_form.is_valid(): criterion_dict = {'book_name': Book.sort_by_book_name, 'author': Book.sort_by_author, 'estimation': Book.sort_by_estimation, 'most_readable': Book.sort_by_readable} category = Category.objects.get(id=sort_form.cleaned_data['category']) books = criterion_dict[sort_form.cleaned_data['criterion']](request.user, category) for book in books: book['name'] = escape(book['name']) book['author'] = escape(book['author']) return HttpResponse(json.dumps(books), content_type='application/json') else: return HttpResponse(status=404) # ----------------------------------------------------------------------------------------------------------------------
def add_comment(request): if request.is_ajax(): comment_form = AddCommentForm(request.POST) if comment_form.is_valid(): comment = BookComment.objects.create(id_user=TheUser.objects.get(id_user=request.user), id_book=Book.objects.get(id=comment_form.cleaned_data['book']), text=comment_form.cleaned_data['comment']) user = TheUser.objects.get(id_user=request.user) user_photo = user.user_photo.url if user.user_photo else '' logger.info("User '{}' left comment with id: '{}' on book with id: '{}'." .format(user, comment.id, comment.id_book.id)) response_data = { 'username': escape(request.user.username), 'user_photo': user_photo, 'posted_date': comment.posted_date.strftime('%d-%m-%Y'), 'text': escape(comment.text) } return HttpResponse(json.dumps(response_data), content_type='application/json') else: return HttpResponse(status=404) # ----------------------------------------------------------------------------------------------------------------------
def load_comments(request): if request.is_ajax(): form = LoadCommentsForm(request.POST) if form.is_valid(): book = Book.objects.get(id=form.cleaned_data['book_id']) comments = BookComment.objects.filter(id_book=book).order_by('-id') next_page_num = form.cleaned_data['page'] + 1 comments_paginator = Paginator(comments, COMMENTS_PER_PAGE) page = comments_paginator.page(next_page_num) json_comments = [{ 'username': escape(comment.id_user.id_user.username), 'user_photo': comment.id_user.user_photo.url if comment.id_user.user_photo else '', 'posted_date': comment.posted_date.strftime('%d-%m-%Y'), 'text': escape(comment.text) } for comment in page.object_list] response_data = { 'comments': json_comments, 'current_page': next_page_num, 'has_next_page': page.has_next(), 'book_id': book.id } return HttpResponse(json.dumps(response_data), content_type='application/json') else: return HttpResponse(status=404)
def assertTextAbsent(self, text): """ Asserts that the text is not present on the current page """ self.assertNotIn(html_norm(escape(text)), html_norm(self.last_response.content.decode('utf-8')))
def assertTextPresent(self, text): """ Asserts that the text is present on the current page """ self.assertIn(html_norm(escape(text)), html_norm(self.last_response.content.decode('utf-8')))
def test_help_with_quotes(self): # Checkboxes get special handling, so test a checkbox and something else res = render_form_field('sender') self.assertIn('title="{}"'.format(escape(TestForm.base_fields['sender'].help_text)), res) res = render_form_field('cc_myself') self.assertIn('title="{}"'.format(escape(TestForm.base_fields['cc_myself'].help_text)), res)
def add_help_attrs(self, widget=None): if widget is None: widget = self.widget if not isinstance(widget, CheckboxInput): widget.attrs['title'] = widget.attrs.get( 'title', escape(strip_tags(self.field_help)) )
def put_inside_label(self, html): content = '{field} {label}'.format( field=html, label=self.field.label, ) return render_label( content=mark_safe(content), label_for=self.field.id_for_label, label_title=escape(strip_tags(self.field_help)) )
def home(request): if request.method == 'GET': return render( request, 'demo/demo.html', ) elif request.method == 'POST' and request.is_ajax(): bname = escape(request.POST.get('board_name')) aid = escape(request.POST.get('article_id')) link = PTT_URL + '/bbs/' + bname + '/' + aid + '.html' if not (bname and aid): return HttpResponse(json.dumps({'data': {'error': 'invalid url'}, 'link': link}), content_type='application/json') if aid.lower() == 'latest' or aid.lower() == 'index': resp = requests.get( url=PTT_URL + '/bbs/' + bname + '/index.html', cookies={'over18': '1'}, verify=False ) if resp.status_code == 200: soup = BeautifulSoup(resp.text) divs = soup.find_all("div", "r-ent") aid = divs[-1].select("div.title > a")[0]['href'].split("/")[3].replace(".html", "") link = PTT_URL + '/bbs/' + bname + '/' + aid + '.html' data = json.loads( crawler.parse(link, aid, bname) ) return HttpResponse(json.dumps({'data': data, 'link': link}), content_type='application/json')
def get_raw_data(self, volume): request = self.table.request link = _('Attached to %(instance)s on %(dev)s') attachments = [] # Filter out "empty" attachments which the client returns... for attachment in [att for att in volume.attachments if att]: # When a volume is attached it may return the server_id # without the server name... instance = get_attachment_name(request, attachment) vals = {"instance": instance, "dev": html.escape(attachment.get("device", ""))} attachments.append(link % vals) return safestring.mark_safe(", ".join(attachments))
def get_raw_data(self, snapshot): volume = snapshot._volume if volume: volume_name = volume.name volume_name = html.escape(volume_name) else: volume_name = _("Unknown") return safestring.mark_safe(volume_name)
def get_raw_data(self, backup): volume = backup.volume if volume: volume_name = volume.name volume_name = html.escape(volume_name) else: volume_name = _("Unknown") return safestring.mark_safe(volume_name)
def test_network_create_post_with_subnet_nocidr(self, test_with_profile=False, test_with_snpool=False): network = self.networks.first() subnet = self.subnets.first() if test_with_profile: net_profiles = self.net_profiles.list() net_profile_id = self.net_profiles.first().id api.neutron.profile_list(IsA(http.HttpRequest), 'network').AndReturn(net_profiles) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'subnet_allocation').\ AndReturn(True) api.neutron.subnetpool_list(IsA(http.HttpRequest)).\ AndReturn(self.subnetpools.list()) self.mox.ReplayAll() form_data = {'net_name': network.name, 'admin_state': network.admin_state_up, 'shared': False, 'with_subnet': True} if test_with_profile: form_data['net_profile_id'] = net_profile_id if test_with_snpool: form_data['subnetpool_id'] = '' form_data['prefixlen'] = '' form_data.update(form_data_subnet(subnet, cidr='', allocation_pools=[])) url = reverse('horizon:project:networks:create') res = self.client.post(url, form_data) self.assertContains(res, escape('Specify "Network Address" or ' 'clear "Create Subnet" checkbox' ' in previous step.'))
def value(self): """Returns a formatted version of the data for final output. This takes into consideration the :attr:`~horizon.tables.Column.link`` and :attr:`~horizon.tables.Column.empty_value` attributes. """ try: data = self.column.get_data(self.datum) if data is None: if callable(self.column.empty_value): data = self.column.empty_value(self.datum) else: data = self.column.empty_value except Exception: data = None exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) if self.url and not self.column.auto == "form_field": link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in self.column.link_attrs.items()]) # Escape the data inside while allowing our HTML to render data = mark_safe('<a href="%s" %s>%s</a>' % ( (escape(self.url), link_attrs, escape(six.text_type(data))))) return data
def object_link(self, obj): ''' if obj.action_flag == DELETION: link = escape(obj.object_repr) else: ct = obj.content_type link = u'<a href="%s">%s</a>' % ( reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]), escape(obj.object_repr) ) ''' return escape(obj.object_repr)
def get_json_data(self, escape_html=False): errors = [] for error in self.as_data(): message = list(error)[0] errors.append({ 'message': escape(message) if escape_html else message, 'code': error.code or '', }) return errors
def item_title(self, item): # Titles should be double escaped by default (see #6533) return escape(force_text(item))
def response_delete(self, request, obj_display, obj_id): """ Determines the HttpResponse for the delete_view stage. """ opts = self.model._meta if IS_POPUP_VAR in request.POST: return SimpleTemplateResponse('admin/popup_response.html', { 'action': 'delete', 'value': escape(obj_id), }) self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % { 'name': force_text(opts.verbose_name), 'obj': force_text(obj_display), }, messages.SUCCESS) if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {'preserved_filters': preserved_filters, 'opts': opts}, post_url ) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url)
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(model._meta.verbose_name), 'key': escape(object_id), }) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model) ).select_related().order_by('action_time') context = dict(self.admin_site.each_context(request), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) request.current_app = self.admin_site.name return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context)
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(model._meta.verbose_name), 'key': escape(object_id), }) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model) ).select_related().order_by('action_time') context = dict( self.admin_site.each_context(request), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) request.current_app = self.admin_site.name return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context)
def clean(self): cleaned_data = super(TeamInvitationForm, self).clean() email = cleaned_data.get("email") if email is None: raise forms.ValidationError("valid email address required") try: user = User.objects.get(email=email) except User.DoesNotExist: # eventually we can invite them but for now assume they are # already on the site raise forms.ValidationError(mark_safe("no account with email address <b>%s</b> found on this conference site" % escape(email))) state = self.team.get_state_for_user(user) if state in ["member", "manager"]: raise forms.ValidationError("user already in team") if state in ["invited"]: raise forms.ValidationError("user already invited to team") self.user = user self.state = state return cleaned_data
def contact(self, sponsor): return mark_safe('<a href="mailto:%s">%s</a>' % (escape(sponsor.contact_email), escape(sponsor.contact_name)))