def emdis_msg_detail(request, msg_id): emsg = get_object_or_404(EmdisMessage, pk=msg_id) if emsg.pre_text: emsg.pre_text = markdownify(emsg.pre_text) if emsg.post_text: emsg.post_text = markdownify(emsg.post_text) return render(request, 'wmdadict/emdis_msg_detail.html', {'emsg': emsg})
def pages(request, page_name='index'): status = 200 base_file = 'base_md.html' page_path_md = path.join(BASE_DIR, 'app', 'pages', page_name + '.md') page_path_html = path.join(BASE_DIR, 'app', 'pages', page_name + '.html') title = page_name.replace('_', ' ').replace('-', ' ').title() data = {'title': title, 'current_date': datetime.now(), 'content': ''} if path.exists(page_path_md): input_file = codecs.open(page_path_md, mode="r", encoding="utf-8").read() data['content'] = markdownify(input_file) elif path.exists(page_path_html): base_file = path.basename(page_path_html) else: page_custom = get_object_or_404(CustomPage, slug=page_name) data['title'] = page_custom.title data['content'] = markdownify(page_custom.content) if page_custom.template == 'P2': base_file = 'base_hero.html' data['icon_url'] = page_custom.icon_url data['subtitle'] = page_custom.subtitle data['description'] = markdownify(page_custom.description) return render(request, base_file, data, status=status)
def appPage(request, name): if name == "inactive": apps = App.objects.all().filter(active=False).order_by('title') top_tags, not_top_tags = findTags() context = { 'apps': apps, 'top_tags': top_tags, 'not_top_tags': not_top_tags, } return render(request, 'apps.html', context) else: app = get_object_or_404(App, name=name) if request.method == 'POST': rating_n = request.POST.get('rating') try: rating_n = int(rating_n) if not (0 <= rating_n <= 5): raise ValueError() except ValueError: raise ValueError( 'rating is "%s" but must be an integer between 0 and 5' % rating_n) app.votes += 1 app.stars += rating_n app.save() return HttpResponseRedirect('/app/' + app.name) if request.method == 'GET': app.description = markdownify(app.description) releases = Release.objects.filter(app=app).order_by('-id') tags = app.tags.all() screenshots = Screenshot.objects.filter(app=app) for release in releases: release.notes = markdownify(release.notes) download = Download.objects.filter(app=app) if download: latest = app.download.default_release else: latest = None compulsory_dependency, optional_dependency = get_dependency( app, latest) editors = app.editors.all() comments = Comment.objects.filter(app=app) go_back_to_url = "/" go_back_to_title = "home" context = { 'app': app, 'editors': editors, 'tags': tags, 'releases': releases, 'screenshots': screenshots, 'latest': latest, 'compulsory_dependency': compulsory_dependency, 'optional_dependency': optional_dependency, # 'comments':comments, 'go_back_to_url': go_back_to_url, 'go_back_to_title': go_back_to_title, } return render(request, 'page.html', context)
def detail(request, id): recipe = get_object_or_404(Recipe, id=id) recipe.ingredients = markdownify(recipe.ingredients) recipe.directions = markdownify(recipe.directions) context = { 'recipe': recipe, } return render(request, 'app/detail.html', context)
def individualTechnique(request, pk): technique = Technique.objects.get(pk=pk) platforms = Platform.objects.filter(technique=technique.technique_id) data_sources = DataSource.objects.filter(technique=technique.technique_id) tactics = Tactic.objects.filter(technique=technique.technique_id) ## Get all notes for a given technique notes = Note.objects.filter(technique_id=technique.technique_id) all_notes = notes[::-1] ## SIGMA RULES sigma_rules = list() rules = SigmaRule.objects.filter(technique=technique.technique_id) rule_names = list() yaml_rule_list = list() for rule in rules: sigma_rules.append("/sigma_rules/" + rule.rule_name + ".yml") sigma = open(settings.MEDIA_ROOT + '/' + rule.rule_file.name, 'r') yaml_rule_list.append([rule.rule_name, sigma.read()]) sigma.close() ## ATOMICS atomic = technique null_atom = "" try: atomic_file = open( settings.MEDIA_ROOT + '/atomics/' + atomic.technique_id + ".md", 'r') atomic_yaml = open( settings.MEDIA_ROOT + '/atomics/' + atomic.technique_id + ".yaml", 'r') atom = atomic_file.read() atom_yaml = atomic_yaml.read() atomic_file.close() atomic_yaml.close() except: null_atom = "There are currently no Atomic Red Team tests available for this technique." atom_yaml = "" atom = "" ## Define the Context context = { 'technique': technique, 'platforms': platforms, 'data_sources': data_sources, 'tactics': tactics, 'technique_description': markdownify(technique.technique_description), 'technique_url': technique.technique_url, 'technique_id': technique.technique_id, 'technique_detection': markdownify(technique.technique_detection), 'technique_name': technique.technique_name, 'atom': markdownify(atom), 'atom_yaml': atom_yaml, 'null_atom': null_atom, 'tech_notes': all_notes, 'yaml_rules': yaml_rule_list, } return render(request, 'matrix/technique.html', context=context)
def get_truncated_content(self): """ Get content between ::begin:: and ::more:: Tags and return it. """ pattern = re.compile(r"(?<=::begin::)(.*)(?=::more::)", re.DOTALL) truncated = self.content[:300] if "::more::" in self.content: truncated = re.search(pattern, self.content) if truncated: return markdownify(truncated.group()) return markdownify(truncated)
def dictionary_detail(request, field_id): dictionaryfield = get_object_or_404(DictionaryField, pk=field_id) dictionaryfield.description_long = markdownify( dictionaryfield.description_long) if dictionaryfield.values: dictionaryfield.values = markdownify(dictionaryfield.values) forms = dictionaryfield.formfields_set.all().distinct('wmda_form') return render(request, 'wmdadict/dictionary_detail.html', { 'dfield': dictionaryfield, 'forms': forms })
def get(self, request): self.bio = Bio.objects.first() self.contact = ContactCard.objects.first() self.projects = Project.objects.all() self.skills_raw = Skill.objects.all() self.skills = [] self.achieves_raw = Achievement.objects.all().order_by('order') self.achieves = [] if self.bio: self.md = markdownify(self.bio.mark_down) if len(self.skills_raw) >= 1: for skill in self.skills_raw: self.skills.append({ 'id': skill.id, 'name': skill.name, 'description': markdownify(skill.description), 'highlights': markdownify(skill.highlights) }) if len(self.skills_raw) >= 1: for achieve in self.achieves_raw: self.achieves.append({ 'id': achieve.id, 'name': achieve.name, 'description': markdownify(achieve.description) }) http_user = self.request.META['HTTP_USER_AGENT'] http_user_clean = http_user.translate(str.maketrans('', '', string.punctuation)) if any(item in http_user_clean.split(' ') for item in mobile_browsers): return render(request, 'home.html', { 'bio': self.bio, 'md': self.md, 'contact': self.contact, 'projects': self.projects, 'skills': self.skills, 'achieves': self.achieves, 'style': 'RossDevs/css/m_style.css', }) elif any(item in http_user_clean.split(' ') for item in desktop_browsers): print('desktop') print(self.request.META['HTTP_USER_AGENT'].translate(str.maketrans('', '', string.punctuation))) return render(request, 'home.html', { 'bio': self.bio, 'md': self.md, 'contact': self.contact, 'projects': self.projects, 'skills': self.skills, 'achieves': self.achieves, 'style': 'RossDevs/css/style.css', })
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'intro_rich': mark_safe(markdownify(self.study.intro)), 'consent_form_text_rich': mark_safe(markdownify(self.study.consent_form_text)), 'contact': mark_safe(self.study.contact), 'contact_details_rich': mark_safe(markdownify(self.study.contact_details)) if self.study.contact_details else None, }) return context
def html_metadata(self, full=False): # Full means "the picture appear with less context than on the species page, so please show all fields. entries = [] if full and self.image_subject: entries.append(self.get_image_subject_display()) if full and self.specimen_stage: entries.append(self.get_specimen_stage_display()) if self.locality: entries.append(self.locality) if self.date: entries.append(str(self.date)) if self.specimen_sex: entries.append(self.get_specimen_sex_display()) if self.side: entries.append(self.get_side_display()) comment_block = '' if self.comment: comment_block = markdownify(self.comment) attributes_block = '' if entries: attributes_block = ', '.join(entries) + '. ' if self.photographer: attributes_block = attributes_block + "© {}<br/>".format( self.photographer.full_name) return '<small>' + '<div class="mb-2">' + attributes_block + '</div><div>' + comment_block + '</div>' + '</small>'
def postView(request, id): # We could check to see if the user has permission to view this post in here # Based on the privacy setting etc. # This is our post object with the given ID # If the post doesn't exist it instantly 404's # This way we won't have to do any taxing database math post = get_object_or_404(Post, pk=id) #pk is primary key # Do not display an image if the image does not exist imageExists = False if post.image_link != "": imageExists = True # Perform privacy calculations # Has permission will be passed in # If its False we could either display a 404 or a "you do not have permission" hasPermission = Services.has_permission_to_see_post(request.user.id, post) if post.is_markdown: post.body = markdownify(post.body) # Post is the post data # imageExists is whether or not there is an image to display # markDown is whether or not to display the plaintext or markdown contents # Has permission determines whether or not to display content to the user post.privacy_setting = Services.get_privacy_string_for_post( post.privacy_setting) return render(request, 'post/post.html', { "post": post, "imageExists": imageExists, "hasPermission": hasPermission })
def article(request, year, slug): """Render an article.""" art = get_object_or_404(Article, date_created__year=year, slug=slug) # redirect to homepage if the art is not published if not art.published: return redirect('blog:home') art_content_html = markdownify(art.content) response = render( request, 'blog/article.html', { 'art': art, 'art_content_html': art_content_html, # 'pop_arts': _get_hot_articles(), 'debug': settings.DEBUG, 'canonical': 'https://{}{}'.format(request.get_host(), art.get_absolute_url()), }) # update article's view count using cookies if request.COOKIES.get( art.slug) is None and not request.user.is_authenticated: import datetime now = datetime.datetime.now() three_days = now + datetime.timedelta(days=3) response.set_signed_cookie(art.slug, art.id, expires=three_days) art.view_count = F('view_count') + 1 art.save() return response
def get(self, request, *args, **kwargs): posts = Post.objects.filter(status='APPROVE').order_by('-timestamp') for post in posts: post.body = markdownify(post.body) return render(request, self.template_name, { 'posts': posts, })
def realm_view(request, realm_slug): realm = get_object_or_404(Realm, realm_slug=realm_slug) realm.description = markdownify(realm.description) new_post = PostEditForm() new_comment = CommentForm() warning = "" if request.method == "POST": new_post = PostEditForm(request.POST) if new_post.is_valid() and request.user.is_authenticated: mode = request.POST.get('mode', None) if mode == 'new': post = new_post.save(commit=False) post.author = request.user post.created_date = timezone.now() post.published_date = timezone.now() post.realm_slug = request.POST.get('realm_slug', None) post.ancestor = request.POST.get('ancestor', None) post.parent = request.POST.get('parent', 0) post.save() warning = "Posted new comment" elif mode == 'edit': post = get_object_or_404(Post, pk=request.POST.get('pk', None)) if request.user == post.author: post.text = request.POST.get('text', None) post.published_date = timezone.now() post.save() warning = "Edited comment" else: warning = "You don't have permission to edit that comment" elif mode == 'delete': post = get_object_or_404(Post, pk=request.POST.get('pk', None)) if request.user == post.author: post.delete() warning = "Deleted comment" else: warning = "You don't have permission to delete that comment" else: warning = 'Can\'t perform that action.' else: warning = 'You must be logged in to comment.' new_post = PostEditForm() pages = Page.objects.filter(realm_slug=realm.realm_slug).order_by('title') posts = Post.objects.filter(realm_slug=realm.realm_slug).filter( parent=0).order_by('-created_date') for post in posts: post.children = Post.objects.filter(parent=post.pk) return render( request, 'realm_view.html', { 'realm': realm, 'pages': pages, 'posts': posts, 'new_post': new_post, 'new_comment': new_comment, 'tech_desc': tech_levels[realm.tech_level - 1], 'magic_desc': magic_levels[realm.magic_level - 1], 'warning': warning })
def list(self, request): queryset = Comment.objects.all() serializer = CommentSerializer(queryset, many=True, context={'request': self.request}) for idx, instance in enumerate(serializer.data): serializer.data[idx]['comment'] = markdownify(instance['comment']) return Response(serializer.data)
def save(self, *args, **kwargs): self.content = markdownify(self.content) if self.is_answer: answer_set = Answer.objects.filter( question=self.question) # 查询当前问题的所有回答 answer_set.update(is_answer=False) # 一律置为未接受 super(Answer, self).save(*args, **kwargs)
def category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) category.description = markdownify(category.description) jobs = Job.objects.all().filter(category=category.id) return render(request, 'jobs/jobs.html', { 'jobs': jobs, 'category': category })
def clean_description(self): data = self.cleaned_data['description'] print(len(data) < 20) if len(data) < 20: raise forms.ValidationError( "Description too Short! Less than 20 words!") data = markdownify(data) return data
def textify(data): """Returns plain text by converting MD to HTML then strips HTML markup and excess spaces / new line characters""" html_data = markdownify(data) text_data = ''.join( BeautifulSoup(html_data, "html.parser").findAll(text=True)) return ' '.join(text_data.replace('\n', ' ').replace('\r', '').split())
def get_page_fragment(context, identifier): """Return rendered HTML for the page fragment with identifier, in the current language""" fragment = PageFragment.objects.get(identifier=identifier) return mark_safe( markdownify(fragment.get_content_in( context.request.LANGUAGE_CODE))) # nosec
def markdown(value, arg=None): markdown_raw = mark_safe(markdownify(value)) if not isinstance(arg, dict) and arg is not None: arg = [arg] for i in arg: markdown_raw = markdown_raw.replace('</{}'.format(i[1:]), '') markdown_raw = markdown_raw.replace(i, '') return SafeText(markdown_raw)
def markdown_to_html(markdown): url = 'https://api.github.com/markdown' r = requests.post(url, json={"text": markdown}, auth=(GITHUB_USERNAME, GITHUB_TOKEN)) if r.status_code == 200: return r.content else: return markdownify(markdown).replace("<code>python", "<code>", 1)
def show_user(request, user_id): user = get_object_or_404(User, pk=user_id) profile = get_object_or_404(UserProfile, user=user) if request.user is not None: user_id = request.user.id else: user_id = 0 if user_id is None: user_id = 0 summary = Status.objects.filter(owner=profile).order_by('-contest') summarylist = [] max_problem = 0 for i in summary: if i.contest.num_of_problem > max_problem: max_problem = i.contest.num_of_problem for i in summary: status = [] ac_s = int_to_strlist(i.ac_status, 4, i.contest.num_of_problem) for j in ac_s: s = '' if j == '1': s = '√' elif j == '2': s = 'O' elif j == '3': s = 'X' status.append(s) while len(status) < max_problem: status.append('') if i.contest.contest_type == 'Onsite': onsite_tag = 1 else: onsite_tag = 0 summarylist.append( templatelist(head=i.contest.id, body=status, tail=i.contest.name, date=i.contest.date, onsite_tag=onsite_tag)) problem = [] for i in range(0, max_problem): problem.append(chr(ord('A') + i)) # summarylist is a list of class consisting of three variable: head, body, tail # each item in summarylist stand for one summary of this contest # head is contest.id of the summary # body is a list of contributor string of each problem # tail is contest.name context = { 'user_c': user, 'user_id': user_id, 'profile': profile, 'summarylist': summarylist, 'problem': problem, 'team_description_markdown': markdownify(profile.team_description) } return render(request, 'users/show_user.html', context)
def markdown(raw_markdown): """Render Markdown as HTML. Args: raw_markdown (str): Text of raw Markdown. Returns: HTML string of rendered Markdown marked as safe. """ return mark_safe(markdownify(raw_markdown))
def gen_summary(self): html = markdownify(self.content) soup = BeautifulSoup(html, 'html.parser') content = soup.text[:300] if len(content) < 300: summary = content else: summary = content.rsplit(' ', 1)[0] + " ..." if summary != self.summary: self.summary = summary
def get_context_data(self, **kwargs): kwargs.update({'n_trial_items': len(self.trial.items)}) context = super().get_context_data(**kwargs) context.update({ 'block_instructions_rich': mark_safe(markdownify(self.questionnaire_block.instructions)), 'next_url': self.next_url, }) return context
def page_view(request, realm_slug, page_slug): page = get_object_or_404(Page, page_slug=page_slug) realm = get_object_or_404(Realm, realm_slug=realm_slug) page.description = markdownify(page.description) pages = Page.objects.filter(realm_slug=realm.realm_slug).order_by('title') return render(request, 'page_view.html', { 'page': page, 'pages': pages, 'realm': realm })
def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) with open('README.md', 'r') as f: data = f.read() context['markdwon'] = markdownify(data) print("====>", context) return context
def project(request, project_pk, course_code=None): project = get_object_or_404(Project, pk=project_pk) course = get_object_or_404(Course, code__iexact=course_code) project.description = markdownify(project.description) return render(request, context={ 'project': project, 'selectedCourse': course }, template_name='students/project.html')
def search(request): query_string = '' found_entries = None if ('q' in request.GET) and request.GET['q'].strip(): query_string = request.GET['q'] entry_query = get_query(query_string, ['title', 'text', ]) found_entries = Post.objects.filter(entry_query, published_date__isnull=False).order_by('-published_date') # isnull = False para no leer los draft sin publicar for post in found_entries: post.text = markdownify(post.text) return render(request, 'blog/post_searched_list.html', {'query_string': query_string, 'posts': found_entries})
def excerpt(self): """ Returns the first 10 words of the post content. First convert markdown to html Then removes all html formatting """ excerpt_list = strip_tags(self.content).split(" ") excerpt = " ".join(strip_tags(markdownify(self.content)).split(" ")[:10]) if len(excerpt_list) > 10: excerpt += " ..." return excerpt
def get_context_data(self, **kwargs): discount_code = self.request.session.get('discount_code') context = super().get_context_data(**kwargs) rates = [] for rate in self.object.filter_rates(discount_code): field = context['form'][rate.name] rates.append({'field': field, 'name': rate.name, 'price': rate.price, 'sold_out': rate.sold_out}) context['rates'] = rates context['workshop'].description = \ markdownify(context['workshop'].description) return context
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) template = Template(self.document.published_content) template_context = Context({ 'domain': settings.SOCIALHOME_DOMAIN, 'email': settings.SOCIALHOME_CONTACT_EMAIL, 'maintainer': settings.SOCIALHOME_MAINTAINER, 'jurisdiction': settings.SOCIALHOME_TOS_JURISDICTION, }) rendered = template.render(template_context) context.update({ 'policy_title': self.document.type.label, 'policy_content': markdownify(rendered), 'policy_version': self.document.published_version, }) return context
def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) post.text = markdownify(post.text) list_documents = {} # buscaremos al autor del post y guardaremos su icono (si lo tiene) user_post = User.objects.filter(username=post.author.username.lower()) # en el diccionario. Lo colocaremos en la firma del post. document = Document.objects.filter(author=user_post) # ahora hacemos lo mismo con los autores de todos los comentarios (si los hay) if document: list_documents.update({document.first().author.username: document.first().docfile.url}) comments = Comment.objects.filter(post=post) for comment in comments: # por cada comentario buscaremos en la BD el autor del mismo user = User.objects.filter(username=comment.author.lower()) # y de ese usuario buscaremos su avatar asociado a su nick document = Document.objects.filter(author=user) if document: list_documents.update({document.first().author.username: document.first().docfile.url}) # si existe avatar, (puede ser que no), lo añadimos al diccionario. return render(request, 'blog/post_detail.html', {'post': post, 'list_documents': list_documents})
def post(self, request, *args, **kwargs): try: order = Order.objects.get(transaction_id=request.POST['unique_id']) order.billed_total = request.POST['amount'] order.billed_datetime = request.POST['date_time'] order.save() # send emails all_orders = order.orderitem_set.all() workshop = all_orders[0].rate.workshop subject = 'Confirmation of payment - %s' % workshop.title plaintext_msg = 'Please enable HTML viewing' contact = '%s <%s>' % (order.contact_name, order.contact_email) attendees = ['%s <%s>' % (i.name, i.email) for i in all_orders] admins = ['%s <%s>' % (i[0], i[1]) for i in settings.ADMINS] body = '<html><h1>%s</h1>' % workshop.title body += '<h2>Workshop Details</h2>' body += '<div>%s</div>' % markdownify(workshop.email_description) body += '<div><h2>Order Details</h2>' body += '<p>Orderer: %s (%s)</p>' % (order.contact_name, order.contact_email) body += '<h3>Orders:</h3><ul>' for oi in all_orders: body += '<li>%s (%s): %s</li>' % (oi.name, oi.email, oi.rate) body += '</ul></div>' body += '</html>' msg = EmailMultiAlternatives(subject, plaintext_msg, '*****@*****.**', to=[contact], cc=attendees, bcc=admins) msg.attach_alternative(body, "text/html") msg.send() except (Order.DoesNotExist, KeyError) as e: logger.error('%s: %s' % (e, request.body)) return HttpResponse(status=400) return HttpResponse()
def post(self, request, *args, **kwargs): compiled_markdown = markdownify(request.POST['content']) return HttpResponse(compiled_markdown)
def content_plaintext_preview(self): # Converting everything to HTML is tedious, so I've truncated the conversion here # No easy way to create plaintext from Markdown - it needs to be converted to HTML first, then stripped down return bleach.clean(markdownify(self.content[:MWPTESTBLOGAPP_TRUNCATE_PREVIEW_CHARS]), tags=[], attributes=[], styles=[], strip=True)
def content_markdowned(self): # return markdowned HTML to render """Returns markdowned content""" return markdownify(self.content)
def get_markdown(self): return markdownify(self.content)
def markdown2html(md): return markdownify(md)
def markdown(value): """ Returns HTML created by markdown language. """ # Use the `markdownify` from `markdownx` to get the same results. return mark_safe(markdownify(value))
def get_queryset(self): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') for post in posts: post.text = markdownify(post.text) return posts
def mkdown(value): return mark_safe(markdownify(value))
def markdownify_filter(value): return mark_safe(markdownify(value))