如何在模板上以人类可读的格式打印数据?

时间:2019-06-07 05:13:40

标签: django

我具有来自API的以下格式的数据:“ 2019-05-29” 我想将其打印为2019年5月29日 以下是我从API收到的文件和响应 API的响应

"Data": [
                {
                    "id": 1,
                    "news_title": "Recent Update",
                    "news_description": "This is recent one line description",
                    "image_id": 1,
                    "news_date": "2018-05-18",
                    "news_content": "the big content",
                    "slug": "recent-update",
                    "company_id": 1,
                    "user_id": 1
                }
            ]

Views.py:

def BlogViews(request,blog_type):
    """
        The blogs are displayed according to the latest, current-month and last-month classification
    """
    blog_type=blog_type.replace('-','_')
    response_blog=requests.get("API" % (settings.BASE_URL,blog_type),headers=headers,verify=False)
    if(response_blog.status_code==200):
        data_blog=response_blog.json()
        if(data_blog['ErrorCode']==0 and data_blog['SubErrorCode']==0):
            blog=BlogYearViews()
            if(len(data_blog['Data'])>0):
                blog_images=BlogImages(data_blog)
                blogs_and_images = zip(data_blog['Data'], blog_images)
                blog_type=blog_type.capitalize()
                blog_type=blog_type.replace('_',' ')
                return render(request,"CombinedBlog.html",{"blogs_and_images": blogs_and_images, "years":blog,"title":blog_type})
            else:
                blog_type=blog_type.capitalize()
                blog_type=blog_type.replace('_',' ')
                return render (request,"NoBlogs.html",{"title":blog_type,"years":blog})
        else:
            return redirect('/404')

CombinedBlog.html

<h2>{{title}} Articles</h2>
<ul>
{% for blog, image in blogs_and_images %}    
<li><h3>{{ blog.news_title }}</h3><br/>     
    <a href="/blog/article/{{ blog.slug }}"><img src="{{ image.image_name }}"/></a><br/>
    <time>{{blog.news_date}}</time><br/>
    <a href="/blog/article/{{ blog.slug }}">click here</a><br/></li>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

Django模板过滤器具有您需要使用的Date filter

格式-{{ value|date:"M d, Y" }}

每月上限(5月)-M

日期(01-31)-d

完整年份(2019)  -Y

<h2>{{title}} Articles</h2>
<ul>
{% for blog, image in blogs_and_images %}    
<li><h3>{{ blog.news_title }}</h3><br/>     
    <a href="/blog/article/{{ blog.slug }}"><img src="{{ image.image_name }}"/></a><br/>
    <time>{{blog.news_date|date:"M d, Y" }}</time><br/>     # <----- use this
    <a href="/blog/article/{{ blog.slug }}">click here</a><br/></li>
{% endfor %}