ETHAN avatar

[Python #10] [Django #3] 获取我的POST列表并显示在网页

june0620

Published: 11 Jul 2020 › Updated: 11 Jul 2020[Python #10] [Django #3] 获取我的POST列表并显示在网页

[Python #10] [Django #3] 获取我的POST列表并显示在网页

pixabay

上期简单的尝试了下把我的STEEM信息投放到网页,今天把我的POSTS放到网页上吧。(#边学边写真难)

添加 URL

首先在blog目录下的 urls.py 添加相关url。用slug来判断并读取Views.py的posts类,用.as_view()来显示ListView。

from django.urls import path
from .views import main_view, posts

urlpatterns = [
    path('', main_view, name='my_home'),
    path('@/', posts.as_view(), name='posts'),
]

image.png

添加类到Views.py

因上面命名了post,所以在 Views.py文件加上相应的类,这个类继承django的ListView。
重定义get函数,这里我们用到 Services.py里的 blog 函数。

from .services import my_data, blogs

class posts(ListView):
    template_name = 'posts.html'
    context_object_name = 'all_posts'

    def get(self, request, *args, **kwargs):
        self.queryset = blogs(kwargs['account'])
        return super().get(request, *args, **kwargs)

image.png

获取 POST 列表

用 steem-python 库调用某人的post列表,填入到 Services.py

from steem import Steem

def blogs(account=str):
    s = Steem()
    blogs = s.get_blog(account, entry_id=0, limit=50)

    return blogs

image.png

创建模板

该创建网页模板了,创建一个叫 templates 的文件夹到 blog 文件夹同级别下,并在之下创建一个 posts.html网页文件。

$ mkdir templates
$ touch templates/home.html

之后在html文件写入如下:

<h1>My Steem Blog</h1>
    <ul>
        {% for post in all_posts %}
            <li><a href="https://www.steemit.com/@{{post.comment.author}}/{{ post.comment.permlink }}" target="_blank">{{ post.comment.title }}</a></li>
        {% endfor %}
    </ul>

image.png
意思就是从 Views.py 获取的目录反复用li标签渲染到页面。
还差一步,需要把 template 路径设置到 Settings.py

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

image.png

运行

运行本地服务器后在 URL 加 @june0620后缀访问,成功。
image.png

.
.
.
.
[Cookie 😅]
Python 3.7.4
Django 2.2.4
steem-python 1.0.1
goorm IDE 1.3

Leave [Python #10] [Django #3] 获取我的POST列表并显示在网页 to:

Written by

Read more #cn posts


Best Posts From ETHAN

We have not curated any of june0620's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ETHAN