使用Django创建一个简单的博客网站的步骤

首先

由于在Django兄弟的教程中学习了Django,所以我将总结一下使用Django创建一个简单的博客网站的步骤。

Django的发展趋势

创建虚拟环境并安装Django。

$ mkdir DjangoBros
$ cd DjangoBros
DjangoBros $ python3 -m venv djangobros_venv
DjangoBros $ source djangobros_venv/bin/activate
(djangobros_venv) DjangoBros $ pip install --upgrade pip
(djangobros_venv) DjangoBros $ pip install django
(djangorbos_venv) DjangoBros $ deactivate

建立一个项目

DjangoBros $ source djangobros_venv/bin/activate
(djangobros_venv) DjangoBros $ django-admin startproject django_blog
(djangobros_venv) DjangoBros $ cd django_blog
(djangobros_venv) django_blog $ python manage.py runserver

改变设置


LANGUAGE_CODE = 'ja-JP'
TIME_ZONE = 'Asia/Tokyo'

迁移/移民

(djangobros_venv) django_blog $ python manage.py migrate

创建一个应用程序

(djangobros_venv) django_blog $ python manage.py startapp blogs

将应用程序注册到项目中的settings.py文件


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blogs',
]

模板

(djangobros_venv) blogs $ mkdir templates
(djangobros_venv) blogs $ cd templates
(djangobros_venv) templates $ mkdir blogs
(djangobros_venv) templates $ cd blogs
(djangobros_venv) templates $ touch index.html

视图.py


from django.shortcuts import render

def index(request):
    return render(request, 'blogs/index.html')

让django_blogs项目的urls.py文件读取blogs应用程序的urls.py文件。


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blogs.urls')),
]

blogs应用的urls.py


from django.urls import path
from . import views

app_name = 'blogs'
urlpatterns = [
    path('', views.index, name='index'),
]

创建数据库

模型.py

from django.db import models

class Blog(models.Model):
    title = models.CharField(blank=False, null=False, max_length=150)
    text = models.TextField(blank=True)
    created_datetime = models.DateTimeField(auto_now_add=True)
    updated_datetime = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

迁移
迁居
移居
迁移 refers to the act of moving or relocating, often used to describe migration on a larger scale, such as the migration of a population or group.
迁居 and 移居 both specifically refer to the act of migrating or relocating one’s residence or living place.

django_blog $ python manage.py makemigrations
django_blog $ python manage.py migrate

创建管理员页面

django_blog $ python manage.py createsuperuser

django/blogs/admin.py 的中文改写如下:
django/博客/管理后台.py


from django.contrib import admin
from .models import Blog

class BlogAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'created_datetime', 'updated_datetime')
    list_display_links = ('id', 'title')

admin.site.register(Blog, BlogAdmin)

访问 http://127.0.0.1:8000/admin

操作数据库

操作练习,指令示例。

$ python manage.py shell

 from blogs.models import Blog

 Blog.objects.all()
 Blog.objects.get(id=1)
 Blog.objects.filter(title__contains="Django")
 Blog.objects.order_by('id')
 Blog.objects.order_by('-id')
 Blog.objects.filter(title__contains="Django").order_by('-id')

 Blog.objects.create(title="コマンドから作られたブログ", text="createメソッドでブログを作ってみました。")

 blog = Blog.objects.get(id=1)
 blog.title

 blogs = Blog.objects.all()
 blogs[0].text

用HTML来显示查询结果集。

视图.py


from django.shortcuts import render
from .models import Blog

def index(request):
    blogs = Blog.objects.order_by('-created_datetime')
    return render(request, 'blogs/index.html', {'blogs': blogs})

首页.html


<h1>ブログサイト</h1>
<p>ここはトップページです。</p>
{% for blog in blogs %}
  {{ blog.title }}
{% endfor %}

如果写得正确的话


<!DOCTYPE html>
<html>
<head>
  <title>ブログ管理サイト</title>
</head>
<body>
  <h1 style="text-align: center;">My Blog</h1>
  <div style="width: 70%;margin: 0px auto;">
    <hr />
    {% for blog in blogs %}
    <div>
      <h3>{{ blog.title }}</h3>
      <div>{{ blog.text | truncatechars:100 }}</div>
    </div>
    <hr />
    {% endfor %}
  </div>
</body>
</html>

创建详细页面

添加到详细页面的链接


<!DOCTYPE html>
<html>
<head>
  <title>ブログ管理サイト</title>
</head>
<body>
  <h1 style="text-align: center;">My Blog</h1>
  <div style="width: 70%;margin: 0px auto;">
    <hr />
    {% for blog in blogs %}
    <div>
      <h3>{{ blog.title }}</h3>
      <div>{{ blog.text | truncatechars:100 }}</div>
      <div style="text-align: right;">
        <a href="{% url 'blogs:detail' blog_id=blog.id %}">記事を読む</a>
      </div>
    </div>
    <hr />
    {% endfor %}
  </div>
</body>
</html>

urls.py 的中文意思是网址.py。


from django.urls import path
from . import views

app_name = 'blogs'
urlpatterns = [
    path('', views.index, name='index'),
    path('detail/<int:blog_id>/', views.detail, name='detail'),
]

视图.py

from django.shortcuts import render
from .models import Blog

・・・

def detail(request, blog_id):
    blog = Blog.objects.get(id=blog_id)
    return render(request, 'blogs/detail.html', {'blog': blog})

模板/详细.html

<!DOCTYPE html>
<html>
<head>
  <title>ブログアプリ</title>
</head>
<body>
  <h1 style="text-align: center;">{{ blog.title }}</h1>
  <div style="width: 70%;margin: 0px auto;">
    <div>
      <div style="margin: 60px 20px;">
        {{ blog.text }}
      </div>
      <div style="text-align: center; margin-top: 50px">
        <a href="{% url 'blogs:index' %}">トップページに戻る</a>
      </div>
    </div>
  </div>
</body>
</html>
广告
将在 10 秒后关闭
bannerAds