def render_tag(self, context, **kwargs): article = kwargs.pop('article', None) if not article: return '' try: lang = get_language_from_request(context['request']) except KeyError: lang = "en" # try to get the article in the correct language, default to RANDOM language if not available body = getattr(article, "body_%s" % lang, None) if not body: body = article.body # first pass, scampi 2.0+ style media tpl = template.Template(u" ".join(["{% load renaissance %}", body]), name="internal_article_tpl") c = template.Context({'article': article}) first_pass = tpl.render(c) # second pass, scampi 1.0 style media inlined_images = article.image_inlines.all() if inlined_images.count() > 0: md_friendly = "\n".join([u"[%s]: %s" % (t.slug, t.file.url) for t in inlined_images]) second_pass = "******".join([first_pass, md_friendly]) else: second_pass = first_pass final = markdown(second_pass) return final
def wikisafe_markdown(value, lsafety=None, rsafety=None): lsafety = lsafety or 'LBRACK666' # Some unlikely nonsense rsafety = rsafety or 'RBRACK666' # Some unlikely nonsense value = value.replace(LEFTBRACKET, lsafety).replace(RIGHTBRACKET, rsafety) value = markdown(value) value = value.replace(lsafety, LEFTBRACKET).replace(rsafety, RIGHTBRACKET) return mark_safe(value)
def markup(value, mtype=1): try: from django.utils.html import escape if mtype == MARKDOWN[0]: try: import markdown2 except ImportError: try: from django.contrib.markup.templatetags.markup import markdown except ImportError: return sanitize_html(force_unicode(value)) return mark_safe(sanitize_html(markdown(force_unicode(value)))) else: safe_mode = False return mark_safe(sanitize_html(markdown2.markdown(force_unicode(value), safe_mode=safe_mode))) elif mtype == TEXTILE[0]: from django.contrib.markup.templatetags.markup import textile return textile(force_unicode(value)) ## elif mtype == REST[0]: ## from django.contrib.markup.templatetags.markup import restructuredtext ## return restructuredtext(value) elif mtype == HTML[0]: return mark_safe(sanitize_html(force_unicode(value))) elif mtype == PLAINTEXT[0]: return escape(force_unicode(value)) else: return markup(value, DEFAULT_MARKUP[0]) except ImportError: # Not marking safe, in case tag fails and users input malicious code. return force_unicode(value)
def get_text(self): if self.format == 'markdown': return markdown(self.text) elif self.format == 'textile': return textile(self.text) return self.text
def readme(repository): """ Return a rendered version of the readme for the given repository """ if not repository.readme or not repository.readme.strip(): return 'No readme :(' readme = None try: if repository.readme_type == 'markdown': readme = markup.markdown(repository.readme) elif repository.readme_type == 'textile': readme = markup.textile(repository.readme) elif repository.readme_type == 'rest': readme = markup.restructuredtext(repository.readme) except: pass if not readme: readme = '<pre>%s</pre>' % urlize(repository.readme) try: result = mark_safe(clean_html(readme)) except: result = 'Unreadble readme :(' return result
def prepare(self): # Set the template and title for the page content, if they are not set (but don't save them) self.title = self.title or self.page.title self.template = self.template or self.page.template self.slug = self.slug or self.page.slug if not self.description: self.description = '' if not self.keywords: self.keywords = '' if not self.page_topic: self.page_topic = '' # Convert the content to HTML if self.content_type == 'html': pass # Nothing to do elif self.content_type == 'markdown': self.content = markdown(self.content) elif self.content_type == 'textile': self.content = textile(self.content) elif self.content_type == 'rst': self.content = rst(self.content) else: self.content = mark_safe(linebreaks(escape(self.content))) self.toc = mark_safe(self.toc) return self
def auto_transform_markup(comment): """ Given a comment (``ThreadedComment`` or ``FreeThreadedComment``), this tag looks up the markup type of the comment and formats the output accordingly. It can also output the formatted content to a context variable, if a context name is specified. """ try: from django.utils.html import escape from threadedcomments.models import MARKDOWN, TEXTILE, REST, PLAINTEXT if comment.markup == MARKDOWN: from django.contrib.markup.templatetags.markup import markdown return markdown(comment.comment) elif comment.markup == TEXTILE: from django.contrib.markup.templatetags.markup import textile return textile(comment.comment) elif comment.markup == REST: from django.contrib.markup.templatetags.markup import restructuredtext return restructuredtext(comment.comment) # elif comment.markup == HTML: # return mark_safe(force_unicode(comment.comment)) elif comment.markup == PLAINTEXT: return escape(comment.comment) except ImportError: # Not marking safe, in case tag fails and users input malicious code. return force_unicode(comment.comment)
def save_model(self, request, obj, form, change): obj.author = request.user if obj.is_html: obj.content_html = obj.content else: obj.content_html = markdown(obj.content) obj.save()
def _output(self): """It is this method that is responsible for rendering the object in HTML. """ if self.text is None or self.text == "": return u"" if self.text_format == '\E': return linebreaks(urlize(escape(self.text))) elif self.text_format == '\T': try: return textile(self.text) except: return mark_safe(_('There is an error in the Textile.')) elif self.text_format == '\M': try: return markdown(self.text, MARKDOWN_EXTENSIONS) except: return mark_safe(_('There is an error in the Markdown.')) elif self.text_format == '\R': try: return restructuredtext(self.text) except: return mark_safe(_('There is an error in the reStructuredText.')) elif self.text_format == '\H' or self.text_format == '\W': return mark_safe(self.text) else: return mark_safe(escape(self.text))
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.body: self.body_html= markdown(self.body) super(Entry, self).save()
def markdownpreview(request): '''Used by Markitup! editor to render the markdown for the preview button. ''' from django.contrib.markup.templatetags.markup import markdown data = markdown(request.POST.get('data', ''), settings.MARKDOWN_EXTENSIONS) return render_to_response( 'pubman/markdownpreview.html', {'preview': data,}, context_instance=RequestContext(request))
def save(self, force_insert=False, force_update=False): if not self.id: self.pub_date = datetime.datetime.now() self.updated_date = datetime.datetime.now() self.description_html = markdown(self.description) # problem with pygments and htmlformatter due to last version # self.highlighted_code = self.highlight() super(Snippet, self).save(force_insert, force_update)
def __init__(self, node, **options): if settings.configured: options.update(getattr(settings,'PYJADE',{})) filters = options.get('filters',{}) if 'markdown' not in filters: filters['markdown'] = lambda x, y: markdown(x) self.filters.update(filters) super(Compiler, self).__init__(node, **options)
def wikisafe_markdown(value): from django.contrib.markup.templatetags.markup import markdown return mark_safe( markdown(value.replace("[[", "LBRACK666").replace("]]", "RBRACK666")) .replace("LBRACK666", "[[") .replace("RBRACK666", "]]") )
def markdownpreview(request): '''Used by Markitup! editor to render the markdown for the preview button. ''' data = markdown(request.POST.get('data', ''), app_settings.MARKDOWN_EXTENSIONS) return render_to_response( 'enhancedtext/markdownpreview.html', {'preview': data,}, context_instance=RequestContext(request))
def html_content(self): """Return the content correctly formatted""" if MARKUP_LANGUAGE == 'markdown': return markdown(self.content, MARKDOWN_EXTENSIONS) elif MARKUP_LANGUAGE == 'textile': return textile(self.content) elif MARKUP_LANGUAGE == 'restructuredtext': return restructuredtext(self.content) return self.content
def render_markup(self): """Turns any markup into HTML""" original = self.rendered_description if self.markup == MARKUP_MARKDOWN: self.rendered_description = markup.markdown(self.description) else: self.rendered_description = self.description return (self.rendered_description != original)
def as_dict(self): return {"pk": self.pk, "name": self.name, "description_markdown": markdown(self.description), "description": self.description, "letter_start": self.letter_start, "letter_end": self.letter_end, "letter_start_form": self.letter_start_form, "letter_end_form": self.letter_end_form, "jurisdiction": self.jurisdiction.name, "jurisdiction_id": self.jurisdiction.id}
def html_content(self): """Return the content correctly formatted""" if MARKUP_LANGUAGE == "markdown": return markdown(self.content, MARKDOWN_EXTENSIONS) elif MARKUP_LANGUAGE == "textile": return textile(self.content) elif MARKUP_LANGUAGE == "restructuredtext": return restructuredtext(self.content) elif not "</p>" in self.content: return linebreaks(self.content) return self.content
def process_markup(text, markup): if markup == 'textile': return textile(text) elif markup == 'html': return mark_safe(text) elif markup == 'markdown': return markdown(text) elif markup == 'rst': return restructuredtext(text) else: return mark_safe('<pre>' + text + '</pre>')
def html_content(self): """Return the Entry.content attribute formatted in HTML""" if MARKUP_LANGUAGE == 'markdown': return markdown(self.content, MARKDOWN_EXTENSIONS) elif MARKUP_LANGUAGE == 'textile': return textile(self.content) elif MARKUP_LANGUAGE == 'restructuredtext': return restructuredtext(self.content) elif not '</p>' in self.content: return linebreaks(self.content) return self.content
def save_model(self, request, obj, form, change): obj.author = request.user if not obj.summary: obj.summary = obj.content if not obj.is_old: obj.content_html = markdown(obj.content) else: obj.content_html = obj.content.replace('\r\n', '<br/>') import re obj.content_html = re.sub(r"\[cc lang='\w+?'\]", '<pre>', obj.content_html) obj.content_html = obj.content_html.replace('[/cc]', '</pre>') obj.save()
def get_markuped_body(self): if not self.syntax: return self.body syntax_name = self.syntax.name if syntax_name == "textile": return textile(self.body) elif syntax_name == "markdown": return markdown(self.body) elif syntax_name == "restructuredtext": return restructuredtext(self.body) else: return self.body
def markup(txt, markupname=0): if markupname is Page.TEXTILE: from django.contrib.markup.templatetags.markup import textile return textile(txt) elif markupname is Page.MARKDOWN: from django.contrib.markup.templatetags.markup import markdown return markdown(txt) elif markupname is Page.RESTRUCTUREDTEXT: from django.contrib.markup.templatetags.markup import restructuredtext return restructuredtext(txt) else: return txt
def markdown(value): u"""Filter for formatting the value by assuming Markdown syntax. Embedded HTML tags are always escaped. Warning: You need at least Python Markdown 1.7 or later so that this works. FixMe: Before Markdown sees the text, all named entities are replaced, see `chantal_common.utils.substitute_html_entities`. This creates a mild escaping problem. ``\&`` becomes ``&amp;`` instead of ``\&``. It can only be solved by getting python-markdown to replace the entities, however, I can't easily do that without allowing HTML tags, too. """ return markup.markdown(escape(utils.substitute_html_entities(unicode(value))))
def markup(text, format): if format == 'html': return mark_safe(text) elif format == 'rest': return markup_filters.restructuredtext(text) elif format == 'mdown': return markup_filters.markdown(text) elif format == 'txtile': return markup_filters.textile(text) elif settings.DEBUG: raise Exception, "Invalid 'markup' format: %s" % format return ''
def __init__(self, node, **options): if settings.configured: options.update(getattr(settings,'PYJADE',{})) filters = options.get('filters',{}) if 'markdown' not in filters: filters['markdown'] = lambda x, y: markdown(x) if COFFEESCRIPT_AVIABLE and 'coffeescript' not in filters: filters['coffeescript'] = lambda x, y: '<script>%s</script>' % coffeescript.compile(x) self.filters = filters super(Compiler, self).__init__(node, **options)
def render_article_translation(context, article, translation): article_template = u"{0:>s} {1:>s}".format("{% load renaissance %}", translation['body']) c = template.Context({'article': article}) try: tpl = template.Template(article_template, name="newsengine.ArticleTranslation private render") rendered = tpl.render(c) except template.TemplateSyntaxError: rendered = translation['body'] return markdown(rendered)
def format_content(value, format): if format=='M': # markdown value = markdown(value, settings.MARKDOWN_EXTENSIONS) elif format == 'R': value = restructuredtext(value) elif format=='H': value = mark_safe(value) else: value = linebreaks(urlize(escape(value))) return value
def process_markdown(request): data = {'success': False} if request.method == 'POST': text = request.POST['text'] data['success'] = True data['html'] = markdown(text) else: data['error_msg'] = 'Wrong request method' json = simplejson.dumps(data) return HttpResponse(json, mimetype='application/json')
def render_frontpage(request): """ Retrieves the most recently updated front-page configuration from the database and renders it. Since this view will process anywhere from a quarter to half our pageviews for a given day, it should be pretty damn fast. Django's template language is nice, but doing processing there is much slower than doing it in the view--so let's do a fair amount of the rendering and processing before we get there. Template: frontpage.html Arguments: None. Context (let's fill this in soon): 'all_blogs' 'calendar' 'calendar_list' 'events' 'event_list' 'issue' 'issue_front' 'issue_other_layouts' 'latest_audio' 'latest_blog_posts' 'latest_multimedia' 'latest_online_exclusives' 'latest_podcast_episodes' 'latest_slideshow' 'latest_video' 'month' 'month_formatted' 'month_minus' 'month_name' 'month_plus' 'news_bursts' 'other_info' 'rotating_item_list' 'rotating_items' 'section_arts' 'section_arts_articles' 'section_forum' 'section_forum_articles' 'section_news' 'section_news_articles' 'section_outlook' 'section_outlook_articles' 'section_sports' 'section_sports_articles' 'this_month' 'this_year' 'today' 'top_articles' 'weekday_header' 'year' 'year_minus' 'year_plus' """ site = Site.objects.get_current() front = WebFront.objects.select_related(depth=1).filter( site=site, type='site').latest() issue = front.issue # For the top articles not in the rotation, we choose from published articles that: # * are on the current site, # * were published on or after the day this issue was published and # * don't have publication dates in the future. articles = Article.get_published.select_related(depth=1).filter( section__publication__site=site).filter( issue__pub_date__gte=issue.pub_date).filter( issue__pub_date__lte=datetime.now()).order_by('priority') # Here we get a list of all five top items, for a JavaScript rotation. # Note we have two variables with this list — this is due to how our # particular rotation is implemented. rotating_items = front.item_set.all() rotating_item_list = front.item_set.all() # Remove the top story from further consideration. #B# This will need to be changed to reflect articles no longer being directly FKed to WebFronts. #articles = articles.exclude(webfronts__webfront=front) top_articles = articles[:4] # Here we get the top five articles from each section. # NOTE: This hard-codes section names in so that we can control # which section appears where in the front page template. #B# This will need to be changed to programatically go through sections. We can now order the sections by their ContentChannel's priority. sections = Section.objects.all().order_by('-priority')[:5] section_list = [] for section in sections: sec_obj = section sec_articles = articles.filter( section=section).order_by('priority')[:5] section_dict = {'sec_obj': sec_obj, 'articles': sec_articles} section_list.append(section_dict) # section_news = Section.objects.get(name='News') # section_news_articles = articles.filter(section=section_news).order_by('priority')[:5] # section_outlook = Section.objects.get(name='Outlook') # section_outlook_articles = articles.filter(section=section_outlook).order_by('priority')[:5] # section_forum = Section.objects.get(name='Forum') # section_forum_articles = articles.filter(section=section_forum).order_by('priority')[:5] # section_arts = Section.objects.get(name='Arts') # section_arts_articles = section_arts.article_set.filter(published=1).order_by('-pub_date', 'priority')[:5] # section_sports = Section.objects.get(name='Sports') # section_sports_articles = articles.filter(section=section_sports).order_by('priority')[:5] # And now we get all blogs that are listed in this publication, and # the three most recent posts in these blogs. all_blogs = Blog.current.filter(section__publication__site=site).all() latest_blog_posts = Entry.get_published.filter( blog__section__publication__site=site)[:3] # Now we get the latest podcast episodes from across all sites. latest_podcast_episodes = Episode.objects.all()[:4] # Here we also get the top three online-only stories that: # * aren't published in the future, # * are marked as Web updates and # * aren't in the rotation. latest_online_exclusives = Article.get_published.filter( issue__pub_date__lte=datetime.now()).filter(type='online') # latest_online_exclusives = latest_online_exclusives.exclude(webfronts__webfront=front) latest_online_exclusives = latest_online_exclusives[:3] # Now to get the most recently released multimedia. try: latest_video = Video.objects.filter(publication__site=site).latest() # latest_video = latest_video.exclude(webfronts__webfront=front).latest() except: latest_video = "" try: latest_slideshow = Slideshow.objects.filter( publication__site=site).latest() # latest_slideshow = latest_slideshow.exclude(webfronts__webfront=front).latest() except: latest_slideshow = "" try: latest_audio = AudioClip.objects.filter( publication__site=site).latest() # latest_audio = latest.audio.exclude(webfronts__webfront=front).latest() except: latest_audio = "" # Compare the video and slideshow to see which one's newer. if latest_slideshow != "" and latest_video != "" and latest_slideshow.pub_date > latest_video.pub_date: latest_multimedia = latest_slideshow else: latest_multimedia = latest_video # Compare the audio and the winner so far to see which one's newer. if latest_audio != "" and latest_multimedia != "" and latest_audio.pub_date > latest_multimedia.pub_date: latest_multimedia = latest_audio # Do we need to show anything else? If so, go ahead and render it. #B# Is this still relevant? If so, make it prominent on the page. other_info = None if front.other_info: other_info = markdown(front.other_info) # Get all events that aren't over and that are in the # appropriate calendar. events = Event.not_past.filter(calendars=front.calendar)[:5] # Get all currently-published news bursts. #B# Should we have different news bursts for each site? news_bursts = NewsBurst.get_published.all() # Get the front page layout from this issue, if there is one. try: issue_front = issue.layout_set.filter(type='cover').filter( section__publication__site=site).latest() except: issue_front = None # Get all other layouts from this issue. issue_other_layouts = issue.layout_set.exclude(type='cover').filter( section__publication__site=site) # And now, the calendar. Nothing too fancy here; a repaste of the code found in # events.views.gridone gets the job done. year = datetime.now().year month = datetime.now().month calendar = None calendar_list = Calendar.objects.all().order_by('name') events = Event.objects.all() month_formatted = pycal.monthcalendar(year, month) month_minus = month - 1 month_plus = month + 1 month_name = pycal.month_name[month] weekday_header = pycal.weekheader(3).strip().split(" ") year_minus = year - 1 year_plus = year + 1 today = datetime.now().day this_month = month this_year = year event_list = events.filter( Q(start__year=year, start__month=month) | Q(end__year=year, end__month=month)) # A reposting of the method to get events from earlier. Because you just # don't want every event THAT WAS EVER PUT IN showing up on the front page. events = Event.not_past.filter(calendars=front.calendar)[:5] #B# Can we do a TopOnline view that can return context here, instead of calling methods ourselves? page = { 'all_blogs': all_blogs, 'calendar': calendar, 'calendar_list': calendar_list, 'events': events, 'event_list': event_list, 'issue': issue, 'issue_front': issue_front, 'issue_other_layouts': issue_other_layouts, 'latest_audio': latest_audio, 'latest_blog_posts': latest_blog_posts, 'latest_multimedia': latest_multimedia, 'latest_online_exclusives': latest_online_exclusives, 'latest_podcast_episodes': latest_podcast_episodes, 'latest_slideshow': latest_slideshow, 'latest_video': latest_video, 'month': month, 'month_formatted': month_formatted, 'month_minus': month_minus, 'month_name': month_name, 'month_plus': month_plus, 'news_bursts': news_bursts, 'other_info': other_info, 'rotating_item_list': rotating_item_list, 'rotating_items': rotating_items, 'sections': section_list, # 'section_arts': section_arts, # 'section_arts_articles': section_arts_articles, # 'section_forum': section_forum, # 'section_forum_articles': section_forum_articles, # 'section_news': section_news, # 'section_news_articles': section_news_articles, # 'section_outlook': section_outlook, # 'section_outlook_articles': section_outlook_articles, # 'section_sports': section_sports, # 'section_sports_articles': section_sports_articles, 'this_month': this_month, 'this_year': this_year, 'today': today, 'top_articles': top_articles, 'weekday_header': weekday_header, 'year': year, 'year_minus': year_minus, 'year_plus': year_plus, } return render_to_response('frontpage/frontpage.html', page, context_instance=RequestContext(request))
def transform_description_html(self, obj, value): from django.contrib.markup.templatetags.markup import markdown return markdown(value)
def short_info_rendered(self): return markdown(self.short_info, 'safe')
This simply re-uses Django's template filters to do the formatting, """ from django.core.exceptions import ImproperlyConfigured from django.contrib.markup.templatetags import markup from django.utils.safestring import SafeData, mark_safe from fluent_contents.plugins.markup import appsettings _languageNames = { 'restructuredtext': 'reStructuredText', 'markdown': 'Markdown', 'textile': 'Textile', } # Copy, and allow adding more options. SUPPORTED_LANGUAGES = dict(markup.register.filters.iteritems()) SUPPORTED_LANGUAGES['markdown'] = lambda text: markup.markdown( text, ','.join(appsettings.FLUENT_MARKUP_MARKDOWN_EXTRAS)) if appsettings.FLUENT_MARKUP_USE_DJANGO_MARKUP: # With django-markup installed, it can be used instead of the default Django filters. # Since most django-markup filters are meant for simple text enhancements, # only use the filters which are really full text markup languages. # Note that the enhanced markdown above will also be replaced. Use the MARKUP_SETTINGS setting to configure django-markup instead. from django_markup.markup import formatter for filter_name, FilterClass in formatter.filter_list.iteritems(): real_filters = _languageNames.keys() + ['creole'] if filter_name in real_filters: _languageNames[filter_name] = FilterClass.title SUPPORTED_LANGUAGES[filter_name] = lambda text: mark_safe( formatter(text, filter_name)) # Format as choices
def custommarkdownfilter(text): # TODO : check if this is safe or di we need "safe" to be added ? # Maybe rewrite markdown to be more flexible return markdown(text, "extra,codehilite,headerid(level=2),sane_lists")
def render(self, context): output = self.nodelist.render(context) return markup.markdown(output, self.args)
def item_description(self, item): return markdown(item.text)
def markdown(text): """Return text rendered as Markdown.""" return Markup(markup.markdown(text, 'safe'))
def item_description(self, item): return markdown(item.content)
def wikisafe_markdown(value): from django.contrib.markup.templatetags.markup import markdown return mark_safe( markdown(value.replace('[[', 'LBRACK666').replace( ']]', 'RBRACK666')).replace('LBRACK666', '[[').replace('RBRACK666', ']]'))
def search_events(request, location=None): ctx = {'title':'Upcoming Events', 'searched':True, 'is_search':True, 'limit':None} ctx['rpp'] = int(request.REQUEST.get('rpp', 10)) location = location or request.location request.location = location # stick user to this location going forward request.location_name = settings.LOCATION_DATA.get(location, settings.EMPTY_LOCATION_DATA)[3] today, td = today_timedelta_by_location(location) qx = Event.objects.active(attending_user=request.user_profile, today=today).order_by('event_date', 'event_start_time', 'pk') loc = request.REQUEST.get("location", None) any_loc = loc == 'any' if not any_loc: # qx = qx.exclude(ext_event_source='mlb2010', location='user-entered') qx = qx.exclude(location='user-entered') # don't show user entered events on city pages f = request.GET.get('filter', '').lower() sort_by = request.GET.get('sort', '').lower() by_date = request.GET.get('date', None) choices = request.GET.getlist('choices') if 'free' in choices: qx = qx.filter(is_free=True) if 'checkins' in sort_by: # Checkins must automatically limit the view to today f = 'today' if f: if not request.user_profile and f in ('favorites', 'my-calendar', 'recommended'): add_message(request, "You will need to sign in first.") return HttpResponseRedirect(u"%s?next=%s" % (reverse("signin"), request.get_full_path())) ctx['filter'] = f if f in ('favorites', 'my-calendar') and request.user_profile: ctx['title'] = "I'm In For:" qx = qx.filter( attendee__attendee_profile=request.user_profile ).distinct().order_by('event_date', 'event_start_time', 'pk') if settings.CALENDAR_FILTER_BY_LOCATION: qx = qx.filter(location__in=('destination', 'user-entered', location)) elif f == 'recommended' and request.user_profile: ctx['title'] = "Friends' Events" qx = qx.filter( recommendedevent__user_profile=request.user_profile ).distinct().order_by('event_date', 'event_start_time', 'pk') if settings.RECOMMENDED_EVENTS_FILTER_BY_LOCATION: qx = qx.filter(location__in=('destination', 'user-entered', location)) elif f == 'most-popular': ctx['title'] = 'Most Popular Events' qx = qx.filter(location=location).order_by('-tweet_count', 'event_date', 'event_start_time', 'pk') elif f == 'our-picks': ctx['title'] = 'Our Picks' qx = qx.filter(location=location).filter(is_homepage_worthy=True).order_by('event_date', 'event_start_time', 'pk') elif f == 'destination': ctx['title'] = 'Destination Events' qx = qx.filter(location='destination').order_by('-destination_timestamp', 'event_date', 'event_start_time', 'pk') elif f == 'today': ctx['title'] = "Today's Events" qx = qx.filter(location=location).filter( event_date=today ).order_by('event_date', 'event_start_time', 'pk') elif f == 'date': # if date not specified, use today dt = by_date and datetime.strptime(by_date, "%m/%d/%Y") or date.today() ctx['title'] = "Events on %s" % dt.strftime("%A, %b %d, %Y") qx = qx.filter(location=location).filter( event_date=dt ).order_by('event_date', 'event_start_time', 'pk') elif f == 'tomorrow': ctx['title'] = "Tomorrow's Events" qx = qx.filter(location=location).filter( event_date=today + timedelta(days=1) ).order_by('event_date', 'event_start_time', 'pk') elif f == 'this-week': ctx['title'] = "This Week" start = today + relativedelta(weekday=MO(-1)) # greater than or equal to last Monday end = start + relativedelta(weekday=SU(+1)) # less than or equal to this Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'this-weekend': ctx['title'] = "This Weekend" start = today + relativedelta(weekday=MO(-1)) + relativedelta(weekday=FR) # greater than or equal to this Friday end = start + relativedelta(weekday=SU(+1)) # less than or equal to this Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'next-week': ctx['title'] = "Next Week" start = today + relativedelta(weekday=MO(-1), weeks=1) # greater than or equal to next Monday end = start + relativedelta(weekday=SU(+1)) # less than or equal to next Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'next-weekend': ctx['title'] = "Next Weekend" start = today + relativedelta(weekday=MO(-1), weeks=1) + relativedelta(weekday=FR) # greater than or equal to next Friday end = start + relativedelta(weekday=SU(+1)) # less than or equal to next Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end else: # no filter if not any_loc: qx = qx.filter(location__in=('destination', 'user-entered', location)) q = request.GET.get('q', '') if q: if not f: ctx['title'] = 'Events matching "%s"' % q ctx['q'] = q qx = qx.filter( Q(title__icontains=q) | Q(description__icontains=q) | Q(venue__name__icontains=q) | Q(hashtag__icontains=q) ) if 'sxsw' in q.lower(): if not request.mobile: ctx['rpp'] = 100 ctx['limit'] = 30 # start with events starting in 30 minutes or more if request.GET.get('page', '1') == '1': prefix = request.mobile and '/mobile/search' or '/help/search' qflat = q.replace('#', '').replace('@', '').lower() for k,v in settings.EVENT_SEARCH_NORMALIZATION.iteritems(): qflat = qflat.replace(k, v) try: flaturl = u"%s/%s/" % (prefix, qflat.replace(' ', '-')) fp = Site.objects.get_current().flatpage_set.get(url=flaturl.lower()) ctx['flatcontent'] = markdown(fp.content) except FlatPage.DoesNotExist: # if this search phrase has multiple space-separated keywords, # look for a flatpage for just the first word. if ' ' in qflat: x = qflat.split(' ') if x[0]: try: flaturl = u"%s/%s/" % (prefix, x[0]) fp = Site.objects.get_current().flatpage_set.get(url=flaturl.lower()) ctx['flatcontent'] = markdown(fp.content) except FlatPage.DoesNotExist: pass if sort_by and 'checkins' in sort_by: ctx['limit'] = 30 limit = request.GET.get('limit', ctx.get('limit', None)) if limit: minutes = int(limit) now = td and (datetime.now() - td) or datetime.now() threshold = now - timedelta(minutes=minutes) time_threshold = threshold.time() _log.debug("Excluding %s events started before %s (limit = %s minutes, td = %s)", today, time_threshold, limit, td) qx = qx.exclude( # event_start_time__isnull=False, # has start time event_date=today, # happened today event_start_time__lt=time_threshold # already happened ) if sort_by and sort_by in ('date', 'tweets', 'interested', 'new', 'checkins', 'mf_checkins', 'fm_checkins'): if 'checkins' in sort_by: # only include events that have no start time or that have already started or that are starting in the next 1 hour now = td and (datetime.now() - td) or datetime.now() threshold = now + timedelta(minutes=settings.CHECKIN_THRESHOLD_MINUTES) # 80 mins from now time_threshold = threshold.time() qx = qx.filter( Q(event_start_time__isnull=True) | Q(event_start_time__lte=time_threshold) ) if sort_by == 'date': qx = qx.order_by('event_date', 'event_start_time', 'pk') elif sort_by == 'tweets': qx = qx.order_by('-tweet_count', 'event_date', 'event_start_time', 'pk') elif sort_by == 'interested': qx = qx.order_by('-stats__num_attendees', 'event_date', 'event_start_time', 'pk') elif sort_by == 'new': qx = qx.order_by('-pk', 'event_date', 'event_start_time') elif sort_by == 'checkins': qx = qx.order_by('-venue__fsq_checkins', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" elif request.user.is_authenticated(): if sort_by == 'mf_checkins': # where the ladies are qx = qx.filter(venue__fsq_checkins__gt=0, venue__fsq_f__gt=1).order_by('venue__fsq_mf', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" elif sort_by == 'fm_checkins': # where the gents are qx = qx.filter(venue__fsq_checkins__gt=0, venue__fsq_m__gt=1).order_by('venue__fsq_fm', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" ctx['sort_by'] = sort_by return list_events(request, location, queryset=qx, extra_context=ctx, hide_top3=True)
def save(self): self.body_html = markdown(self.body_markdown, safe_mode = False) super(Entity,self).save()
def item_description(self, statement): return markdown(statement.text)
def text_html(self): return mark_safe(markdown(r_statement_affil.sub(statement_affil_link, self.text)))
def markdown_filter(x, y): return markdown(x)
def get_gco_help(url='/help/artist/gco/instructions/'): from django.contrib.markup.templatetags.markup import markdown page = Site.objects.get_current().flatpage_set.get(url=url) return _GOOGLE_MERCHANT_ID_HELP_WITH_LINKS % unicode(markdown( page.content))
def format_text(value): return twitterize(urlizetrunc(markdown(value), 30))
def abstract_rendered(self): return markdown(self.abstract, 'safe')
def description_rendered(self): return markdown(self.description, 'safe')