[PYTHON] Use Django's Markdownx outside of site root

Django uses a package called Markdownx that allows you to debug sources written in Markdown notation with a preview. That's pretty handy, but Markdownx doesn't work if your Django project is deployed outside of the site root.

For example

apache2.conf


WSGIScriptAlias /prefix /django/project/project/wsgi.py

If it looks like, the URL of Markdownx is It's a problem if it doesn't look like / prefix / markdownx / markdownify, but since the Markdownx code uses the fixed value in markdownx / settings.py, / markdownx I get 404 when I try to access / markdownify.

To avoid this, do the following.

  1. In the project ʻurls.py`, specify namespace for include of markdownx (let's call it markdownx)
  2. Rewrite the URL part of ʻattrs.update in markdownx / widgets.py with reverse ()

In the explanation of Markdownx that gets stuck in the search, there are some that do not specify namespace in ʻurl patterns`, so specify namespace as follows.

settings.py


urlpatterns = [
    path('markdownx/', include(('markdownx.urls','markdownx'))), 
      :

Next, markdownx / widgets.py (in the site-packages of each environment), but the original is as follows. (When you say where it is, it ’s a classic find, sudo find / -name 'widgets.py' | grep markdownx Let's find it at. settings.py is also there. )

widgets.py(original)


attrs.update({
    'data-markdownx-editor-resizable': MARKDOWNX_EDITOR_RESIZABLE,
    'data-markdownx-urls-path': MARKDOWNX_URLS_PATH,                  
    'data-markdownx-upload-urls-path': MARKDOWNX_UPLOAD_URLS_PATH,             
    'data-markdownx-latency': MARKDOWNX_SERVER_CALL_LATENCY
})

Uppercase variables are defined as constants in markdownx / settings.py and are imported at the beginning of widgets.py. Of these, rewrite the two ending with _URLS_PATH as follows.

widgets.py(After modification)


from django.urls import reverse
       :
attrs.update({
    'data-markdownx-editor-resizable': MARKDOWNX_EDITOR_RESIZABLE,
    'data-markdownx-urls-path': reverse('markdownx:markdownx_markdownify'),
    'data-markdownx-upload-urls-path': reverse('markdownx:markdownx_upload'),
    'data-markdownx-latency': MARKDOWNX_SERVER_CALL_LATENCY
})

Now you can use Markdownx even if you're deploying Django outside of your site root.

Well, there may not be many examples of using it other than the site root, but this time I was a little addicted to the fact that it was additionally deployed to the existing PHP site (this is the site root).

Recommended Posts

Use Django's Markdownx outside of site root
Convenient use of ipython
Graceful use of MySQLdb
LGTM outside of Qiita