Add background management friend chain and whole station announcement function to personal blog

Time:2020-1-2

Add the function of friendship link and announcement notice to personal blog website, write an article to record.

First of all, we consider the use of Django’s template tags, which is also for practice. You can check the official Django documents for relevant knowledge. The following is the specific implementation.

Friendship link function

Model

In fact, the friendship link can be written directly in the HTML of the homepage (I haven’t got the friendship chain up to now), but I want to manage this data through the background, so I built a special name namedextrasOfapp

python manage.py startapp extras

editmodels.pyDocument:

from django.db import models
from model_utils.models import TimeStampedModel
from django.utils.translation import gettext_lazy as _

# Create your models here.
class FriendLink(TimeStampedModel):
    site_name = models.CharField(_('site_name'), max_length=100)
    site_domain = models.URLField(_('site_domain'))

    def __str__(self):
        return self.site_name

TimeStampedModelIs a providerSelf updatingThe abstract base class for creating and modifying fields. Theregettext_lazyIt’s used for internationalization. It’s useless for my little broken station. The reason for this is that IDreamerI’m too lazy to change it.

Don’t forget the model after you write the codetransfer

Template tag

What we use here isInclude tags, first create it in the app directorytemplatetagsDirectory and create__init__.pyThe file makes it a package. Then createsidebar_tags.py, in which to write our Python code.

from django import template
from ..models import FriendLink


register = template.Library()

@register.inclusion_tag('inclusions/_friend_link.html', takes_context=True)
def show_friend_links(context, num=5):
    friend_link_list = FriendLink.objects.all()[:num]
    return {
            'friend_link_list': friend_link_list
    }

The default display is 5 pieces of data. Django template label canReceiving parametersLike{% show_friend_links 5 %}Use in this way.

Note that the inclusion label is used here,@register.inclusion_tag('inclusions/_friend_link.html', takes_context=True)The path of the template to be included is written in the decorator. Include tags display data by rendering the included template.

So you need totemplatesCreate a new file in the folder:

<div class="card mb-4 hvr-glow" style="display: flex">
    <div class="card-body">
        <p class="card-title text-muted">
            < I class = "Fas FA link" style = "color: LightPink;" > links
        </p>
        {% if friend_link_list %}
            {% for link in friend_link_list %}
            <p class="card-text hvr-forward col-12">
                <a href="{{ link.site_domain }}" target="_blank" class="text-muted no-underline">
                    {{ link.site_name }}
                </a>
            </p>
            {% endfor %}
        {% endif %}
    </div>
</div>

UsedbootstrapOfcardThe style is better.

Next, use it where you need to use it{% load sidebar_tags %}Load tags, use where you need to add{% show_friend_links %}Just fine.

Announcement function of the whole station

In the same way, this is also put into the extended function app.

Model

class SiteMessage(TimeStampedModel):
    Content = models. Textfield (verbose "name =" body ")
    
    class Meta:
        Verbose? Name? Plural = 'notification'

    def __str__(self):
        return self.content[:20]

Same useTimeStampedModelSave creation time, programmers just want to be lazy, cheerleading~

Again, when you’re donetransfer

Label

#To import this sitemessage class
from ..models import FriendLink, SiteMessage


@register.inclusion_tag('inclusions/_site_message.html', takes_context=True)
def show_site_message(context):
    try:
        message = SiteMessage.objects.last()
        data = {
                'content': message.content.replace("\r\n", "<br/>"),
                'created': message.created.strftime("%Y/%m/%d"),
        }
    except:
        data = {
                "Content": "O (╥ ﹏) O server connection failed ~"
        }
    return data

adoptSiteMessage.objects.last()Only the latest data is taken each time. The method of use is the same as above.

Design sketch

Add background management friend chain and whole station announcement function to personal blog

About page structure

I spent a lot of time in order to coordinate the page display. The front end is really broad and profound (too difficult).

  1. At the beginning, I had twobase.htmlFiles, one with sidebar, one without, inherit as needed.
  2. Then I willbase.htmlModified, fixed sidebar, placed in{% block side %}{% endblock side %}In the article details page, the sidebar needs a table of contents, which is used under the table of contents{% block.super %}To display the contents of the parent.
  3. Previously, I wanted to make the content sidebar fixed on the page with the mouse scrolling, and the other two sidebars would disappear automaticallybootstrapHowever, it was later found that the content of the sidebar should be displayed more, and all of them should be placed in the sticky sidebar.
  4. There’s only one in the endbase.htmlFile (when I wrote this article, I found that I forgot to delete the useless one…) , and put the sidebarblockIt’s removed.

The code is placed on the Github, focusing on the public address to view the Github address at the bottom menu.

Scan code concernThe daily life of Childe governmentSee the latest push the first time:
Add background management friend chain and whole station announcement function to personal blog