Diango project-simple personal blog project

  • Project implementation function

  1. Customize and add upload documents in the admin background.
  2. Display the articles displayed on the home page in pages.
  3. Click the read full text button of the article on the homepage to enter the full text details page of the article for browsing.
  4. Implemented content classification for articles and archived classification based on publication time.
  5. Use Django's whoose search engine to search for full-text content.
  • Project involves technology

Mysql   Django   Python redis

  • Project core implementation process

  1. Determine the style and layout of the articles to be published (time, author, tag, category, introduction, etc.), and determine the corresponding field form in Django models (note the correspondence between tables and fields, one To-many OR many-to-many, for example, articles and categories can achieve many-to-one (one category contains multiple article types), and there is a many-to-many relationship between articles and tags)
  2. object.get.all() obtains the object content of the database and displays it in a loop on the front-end page of the homepage. As for clicking the read full text button to enter the details page, after the URL is given the route path('page/<int: num>',views.queryAll), here we get the content of the article based on the ID of the different articles identified by clicking.

    postid = int(postid)
    # Query the details of the post based on postid
    post = Post.objects.get(id=postid) then On the detailed content page, post the article. Various fields (category, introduction, content, time, etc.) can be placed in the corresponding change text of the page.

  3. Pagination: Use Django's built-in Pagintor. The technical steps are as follows, combined with the data in the database that needs to be displayed in your own project. 1. Import the Paginator class and the EmptyPage and PageNotAnInteger exception classes; 2. Obtain the data list that needs to be paginated; 3. Create a Paginator object and specify the number of data items displayed on each page; 4. Get the current page number, if not obtained, the default is the first page; 5. Get the data of the current page, if the page number is not an integer or exceeds the range, it will be thrown Exception; 6. Determine the displayed page number range based on the total number of pages; 7. Pass the paging data to the template for rendering

  4. Archiving of articles (by category, time),

     #1.获取分类信息
        r_catepost         =Post.objects.values('category__cname','category').annotate(c=Count('*')).order_by('-c')
        #2.近期文章
        r_recpost = Post.objects.all().order_by('-created')[:3]
        #3.获取日期归档信息
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("select created,count('*') c from t_post GROUP BY         DATE_FORMAT(created,'%Y-%m') ORDER BY c desc,created desc")
        r_filepost = cursor.fetchall()

        The above code is used to obtain specified content objects in the database with different division characteristics.

        Category URL:

        <a class="category-list-link"
        href="/post/category/{ { cp.category }}">{ { cp.category__cname }}</a>

        ​​​​Archive URL:

        <a class="archive-list-link"
        href="/post/archive/{ { fp.0|date:'Y' }}/{ { fp.0|date:'m' }}">{ { fp.0|date:'Y年m月' }}</a>

        Recent article url (same as reading the full text link address): <a href="/post/post/{ { rp.id }}" target="_blank">{ { rp.title|truncatechars:10 }}</a>

     5. To share, just call Baidu Sharing API interface directly: the code is as follows:

        <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div>
        <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到:","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
        </div>

     6: Global search (whoose);

Using Whoosh search in Django requires the django-haystack module. First, you need to install django-haystack and Whoosh. You can use the pip install django-haystack Whoosh command to install it. After the installation is complete, you need to configure it in the settings.py file, including the type, path and other information of the search engine. Next, you need to define the search model, that is, in which models to search. Finally, you need to define the search view and template, that is, how the search results are displayed. For specific usage methods, please refer to the official documentation of django-haystack

  • Project part code:

  1. Pagination:
    def queryAll(request, num=1):
        num = int(num)
        postList = Post.objects.all().order_by('-created')
        # 创建分页器对象
        pageObj = Paginator(postList, 2)
        # 获取当前页的数据
        perPageList = pageObj.page(num)
        # 生成页码数列表
        # 每页开始页码
        begin = (num - int(math.ceil(10.0 / 2)))
        if begin < 1:
            begin = 1
        # 每页结束页码
        end = begin + 9
        if end > pageObj.num_pages:
            end = pageObj.num_pages
        if end <= 10:
            begin = 1
        else:
            begin = end - 9
        pageList = range(begin, end + 1)
        return render(request, 'index.html', {'postList': perPageList, 'pageList': pageList, 'currentNum': num})

  2. Global search:
    #coding=UTF-8
    from  haystack import indexes
    from post.models import *
    import sys  # 导入sys模块
    sys.setrecursionlimit(3000)  # 将默认的递归深度修改为3000
    #注意格式(模型类名+Index)
    class PostIndex(indexes.SearchIndex,indexes.Indexable):
        text = indexes.CharField(document=True, use_template=True)
    
        #给title,content设置索引
        title = indexes.NgramField(model_attr='title')
        content = indexes.NgramField(model_attr='content')
    
        def get_model(self):
            return Post
    
        def index_queryset(self, using=None):
            return self.get_model().objects.order_by('-created')

    tokenizer.py

    #coding=utf-8
    import jieba
    from whoosh.analysis import Tokenizer, Token
    class ChineseTokenizer(Tokenizer):
        def __call__(self, value, positions=False, chars=False,
                     keeporiginal=False, removestops=True,
                     start_pos=0, start_char=0, mode='', **kwargs):
    
            t = Token(positions, chars, removestops=removestops, mode=mode,
                      **kwargs)
            seglist = jieba.cut(value, cut_all=False)  # (精确模式)使用结巴分词库进行分词
            # seglist = jieba.cut_for_search(value)  #(搜索引擎模式) 使用结巴分词库进行分词
            for w in seglist:
                # print w
                t.original = t.text = w
                t.boost = 1.0
                if positions:
                    t.pos = start_pos + value.find(w)
                if chars:
                    t.startchar = start_char + value.find(w)
                    t.endchar = start_char + value.find(w) + len(w)
                yield t  # 通过生成器返回每个分词的结果token
    
    def ChineseAnalyzer():
        return ChineseTokenizer()

  • Screenshot of project part

  • Conclusion:

I wrote it in a bit of a hurry, so I didn’t write out the specific content in detail. I just briefly mentioned it, such as the use of Pagintor paging and the use of whoose global search. I will explain the specific technology next time when I have time. This small project was written at that time. Let me review the technical content related to Django. I apologize for not writing it well.

Guess you like

Origin blog.csdn.net/Abtxr/article/details/134181269