Django: Building a Personal blog (part 3)

[TOC]

Background optimization

1. Apply Sinicization

  • The background localization

    Modify the language and time zone in the Settings file:

    LANGUAGE_CODE = 'zh-hans'
    TIME_ZONE = 'Asia/Shanghai'
    Copy the code
  • Form localization

    Modify the application configuration information in blog/apps.py:

    class BlogConfig(AppConfig) :
        name = 'blog'
        verbose_name='blog'
    Copy the code

    Modify the registration information of the blog application in the Settings file:

    INSTALLED_APPS = [
        ...
        'blog.apps.BlogConfig'.Register the configuration information of the blog application
    ]
    Copy the code
  • Model name localization

    Using the Category example, change the model name with the inner class Meta:

    class Category(models.Model) :
        name = models.CharField(max_length=20)
        class Meta:
            verbose_name = 'classification'
            verbose_name_plural = verbose_name  # the name of a complex number, if not overridden, automatically adds s
    Copy the code
  • Localization of model attributes

    Using Post as an example, add the verbose_name parameter to each attribute:

    title = models.CharField('title', max_length=40)  # 'title' is passed to verbose_name as the first positional argument
    tag = models.ManyToManyField(Tag, verbose_name='tags')  Since the first argument to the associated attribute must be the associated class, we use the keyword argument
    Copy the code

2. Information such as creation time is automatically filled in

  • Creation time: Pass in the current time with the default parameter

    from django.utils import timezone
    createdTime = models.DateTimeField('Creation time', default=timezone.now())  The default value is the current time. Timezone. now can be adjusted to the timezone
    Copy the code
  • Change time: Overrides the save method of Post’s parent Model class

    def save(self, *args, **kwargs) :
        self.modifiedTime = timezone.now()  Change the change time every time you save the instance
        super().save(*args, **kwargs)
    Copy the code
  • Author: overrides the save_model() method of ModelAdmin, the parent of admin.py/PostAdmin

    admin.site.register(Post, PostAdmin)  Register PostAdmin with Post
    
    class PostAdmin(admin.ModelAdmin) :
        def save_model(self, request, obj, form, change) :
            obj.author = request.user  # request.user is the currently logged in user
            super().save_model(request, obj, form, change)
    Copy the code
  • List_display and fields can be modified by modifying the list_display and fields attributes of PostAdmin

    class PostAdmin(admin.ModelAdmin) :
        # Post displays the properties of the form
        list_display = ['title'.'createdTime'.'modifiedTime'.'category'.'author']
        # Post the attribute that the form needs to be filled out manually
        fields = ['title'.'body'.'excerpt'.'category'.'tag']
    Copy the code

Markdown syntax support

The data stored in the database is raw data, and it is expected to be displayed in accordance with the Markdown syntax. Modify the view function as follows:

import markdown
from django.utils.text import slugify
from markdown.extensions.toc import TocExtension
def detail(request, pk) :
    post = get_object_or_404(Post, pk=pk)
   	Instantiate a Markdown object, adding some extra syntax such as code highlighting
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra'.'markdown.extensions.codehilite'.Remember to introduce TocExtension and Slugify at the top
        TocExtension(slugify=slugify),
    ])
    post.body = md.convert(post.body)
    m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
    Add a TOC attribute for POST that can be called in the template to display the directory
    post.toc = m.group(1) if m is not None else ' '
    return render(request, 'blog/detail.html', context={'post': post})
Copy the code

Because of Djangos security mechanism, calling post.body in the detail template requires the safe filter to tell Django that the text is rendered properly:

{{ post.body|safe }}
Copy the code

Continue to add code highlighting references to get the blog to support Markdown syntax and code highlighting

Automatic summary generation

To automatically generate article summaries, you can override the SAVE method of the Post model just as you would automatically generate modification times.

from django.utils.html import strip_tags
def save(self, *args, **kwargs) :
    self.modifiedTime = timezone.now()
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra'.'markdown.extensions.codehilite',]),# strip_tags Can strip HTML text of its tags
    self.excerpt=strip_tags(md.convert(self.body))[:300]
    super().save(*args, **kwargs)
Copy the code