ali60vip
ali60vip

Reputation: 430

Using Django Template Tags in Markdown

I am using Markdown to format/style my blog posts in Django. The problem is that the Django template tags in Markdown don't seem to work for me. More details:

details.html (my blog posts template file)

{% block content %}
    ...
    </p>
    {{ post.body|markdown }}
    <p>
    ...
{% endblock %}

Next, in the body of my blog post, I tried to add an HTML tag that includes a django template tag:

<img src="{% static '/img/image.jpg' %}" alt="image">

enter image description here

and I see this in the result:

enter image description here

Other details:

views.py

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                                    status='published',
                                    publish__year=year,
                                    publish__month=month,
                                    publish__day=day)

    # List of active comments for this post
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
        # A comment was posted
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # create comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # assign the current post to the comment 
            new_comment.post = post
            # save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.postgres',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'blog.apps.BlogConfig',
    'main.apps.MainConfig',
    "crispy_forms",
    "crispy_bootstrap5",
    'taggit',
]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Any ideas what I'm doing wrong?

Upvotes: 2

Views: 329

Answers (1)

ali60vip
ali60vip

Reputation: 430

I converted the Django tag to HTML and it worked.

What I tried and didn't work in my Markdown:

<img src="{% static '/img/my_images/flower.jpg' %}">

What I tried and worked in Markdown:

<img src="/static/img/my_images/flower.jpg' %}">

The 'static' folder is in another App. It seems that Django HTML code is smart enough to trace the folder based on my settings.py instructions.

Upvotes: 1

Related Questions