简体   繁体   中英

Django: Which method or function should be overriden to apply markdown2 to generic view rendering?

I am able to apply Markdown2 to convert marked down text from the database to HTML that is rendered on a template html page.

relevant code :

views.py

page = entry.content
page_converted = markdown2.Markdown().convert(page)
context = {'mdentry': page_converted, "subject":subject}
return render(request, "wikiencyc/md_entry.html", context)

md_entry.html

{% block content %}
{{ mdentry|safe }}
{% endblock %}

The problem is how do I apply the Markdown2 conversion to a generic DetailView where all the boilerplate python code is in the django server code. I understand that I would have to find the relevant method or function within the django server code and override it as a local method in the generic view to accomplish the Markdown2 conversion. Right now, the detailview class is just:

class EntryDetailView(generic.DetailView):
    model = Entry
    slug_field = 'subject'
    slug_url_kwarg = 'subject'

The rest of the functionality to render the object to a view is embedded in the django server code. I need access to the relevant code to override it as local method to get the Markdown2 conversion. Which method of which class would it be? Or, can the markdown2 conversion be done directly on the template somehow?

The content(self, value) method in the HttpResponse(HttpResponseBase) class that is in the response.py of the http: package may be a good candidate method to overrıde. The code is depicted below.

    @content.setter
def content(self, value):
    # Consume iterators upon assignment to allow repeated iteration.
    # print("line 314 in response, value = ", value)
    if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):
        content = b''.join(self.make_bytes(chunk) for chunk in value)
        if hasattr(value, 'close'):
            try:
                value.close()
            except Exception:
                pass
    else:
        content = self.make_bytes(value)
    # Create a list of properly encoded bytestrings to support write().
    self._container = [content]

I am not sure how to parse the content in order to convert the subset of text to HTML. Any help greatly appreciated.

UPDATE Sept 7 2020:

On suggestion in 1st answer, markdown can be done in the template. This is much simpler and makes much more sense. Per suggestion, I added django_markdown2 to the INSTALLED_APPS, and implemented said markdown syntax to the template tags.

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wikiencyc',
'django_markdown2',
]

entry_detail.html

{% load md2 %}
<h4>{{ entry.subject }} </h4>
<br><br>
<p>
   {{ entry.content|markdown:"safe" }}
</p>

However, the django server would not start and I get a long string of exceptions in response to the python manage.py runserver command. If I comment out the 'django_markdown2', from the INSTALLED_APPS , the django server starts up fine but I get the following exception when the app tries to load md2 in the template:

Request Method: GET
Request URL:    http://127.0.0.1:8000/wikiencyc/entry/8
Django Version: 3.0.8
Exception Type: TemplateSyntaxError
Exception Value:    
'md2' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
cache
i18n
l10n
log
static
tz

According to this source , I need to

Place django_markdown2 somewhere in your PYTHONPATH

I have no experience in dealing with the PYTHONPATH. I am using Windows 7 as OS, Python version 3.8, and Django version 3.0.8 .

How do we add the django_markdown2 to PYTHONPATH? Any help greatly appreciated.

You can use Markdown2 directly in the template. First be sure to add django_markdown2 to your INSTALLED_APPS . Then in your template add {% load md2 %} at the top. Then you can render markdown using the template tag like {{ page.content|markdown }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM