整理[Django]的命令和角色

创建项目

django-admin startproject {プロジェクト名}

创建应用程序

在manage.py所在的目录中,执行以下命令

python manage.py startapp {アプリ名}

创建用于URL的目录

from django.urls import path

from . import views

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

{项目名称}/urls.py

在这个urlpatterns中,您可以编写来自每个应用程序的URLConf。

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

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

不同的配置

时区和语言代码

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

创建数据库

使用 migrate 命令,根据文件中的数据库设置创建所有必需的数据库表格。

python manage.py migrate

将模型投射/反映出

python manage.py makemigrations {アプリケーション名}

通过执行`makemigrations`命令,可以告知Django模型发生了更改,并以保存这些更改的方式进行反映。

关于Django管理后台

Django Admin是管理员可以从浏览器中编辑只有管理员可以访问的网站信息的页面。
只有管理员可以创建管理用户才能访问admin网站。

python  python manage.py createsuperuser

启动管理服务器

image.png

使得可以在管理员上编辑应用程序。

要使应用程序能够在admin上进行编辑,需要编辑{应用程序名称}/admin.py文件。
例如,如果要告诉admin接口Question对象具有admin界面,可以按照以下方式编写。

from django.contrib import admin

from .models import Question

admin.site.register(Question)

概述

视图是指…

在Django应用程序中,网页的”类型(type)”是提供特定功能的页面。
在博客应用程序中,应该有以下类型的视图。

    • Blog ホームページ – 最新エントリーをいくつか表示

 

    • エントリー詳細ページ – 1エントリーへのパーマリンク (permalink) ページ

 

    • 年ごとのアーカイブページ – 指定された年のエントリーの月を全て表示

 

    • 月ごとのアーカイブページ – 指定された月のエントリーの日をすべて表示

 

    • 日ごとのアーカイブページ – 指定された日の全てのエントリーを表示

 

    コメント投稿 – エントリーに対するコメントの投稿を受付

在Django中的视图

在Django中,网页和内容通过视图来提供。每个视图都简单地实现为Python函数。

在Django中,还是根据请求的URL来确定视图。为了从URL获取视图,Django使用”URLconf”。

from django.http import HttpResponse

def index(request):
    return("Hello,world.You`re at athe polls index.")

# Create your views here.
def detail(request, question_id):
    return HttpResponse("You`re looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You`re voting on question %s" % question_id)

假设我们创建了类似的视图。

将这些视图与{应用名称}/urls模块进行关联。

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

请按照路径(URL模式,执行方法,名称标签)的顺序进行编写。
这些将从根URL开始搜索。
在这里。

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

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

当请求到达时,Django会在{项目名称}/urls.py文件的urlpatterns变量中进行搜索,然后执行路径模式匹配,接着再次搜索urlpatterns变量,最后执行路径模式匹配方法。

具體運作的視圖

每个视图都有以下两个作用:
– 返回包含页面内容的 HttpResponse 对象。
– 引发类似于 Http404 的异常。

其余的处理取决于用户的选择。

对Django而言,HttpResponse只有两种可能性:存在或者是异常。

项目模板

在{项目名称}/setting.py文件中,记录了Django如何加载模板并对显示内容进行格式化(渲染)的信息。
在默认的配置文件中,设置了DjangoTemplates后端。
当APP_DIRS被设置为TRUE时,DjangoTemplates会搜索每个INSTALLED_APPS中的”templates”子目录。

在创建的应用程序目录中创建一个名为“templates”的目录。
然后在templates目录中创建一个与应用程序名称相同的子目录,并在其中创建一个名为“index.html”的文件。

如果按照公式教程,将应用程序名称命名为polls,那么目录结构将如下所示。

polls/
└ templates/
  └ polls/
    └ index.html

这个有以下的原因。

Django会使用匹配到的第一个模板。如果不同应用程序中存在同名的模板,Django将无法区分它们。获取正确模板的最简单方法是为它们分配命名空间。

如果要将模板应用到视图上,请按照以下方式进行说明。

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html') # templateをロード
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request)) # コンテキストを渡す

快捷方式:render()

如果每次都要导入loader和HttpResponse,那真是太麻烦了。
对于这种情况,我推荐你使用render方法。
只需要导入from django.shortcuts import render,
就可以使用loader和HttpResponse了。

快捷方式:获取或返回404错误

如果执行get()时对象不存在,则抛出Http404,这是非常常见的方法。

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

这个 `get_object_or_404` 函数

try:
    question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
    raise Http404("Qeustion does not exit")

将其简化为省略的形式。

URL之間的命名空間

假设对于 polls 应用而言,它包含有一个详情视图,在同一个项目中也有一个用于博客的应用,该应用可能也包含有同名的视图。那么当使用 {% url %} 模板标签时,Django 应该为哪个应用的视图创建 URL 呢?
我们可以通过在 URLconf 中添加命名空间来告知 Django。

在{应用程序名}/urls.py文件中添加app_name以设置应用程序的命名空间。

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

列表视图和详细视图

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above, no changes needed.

ListView用于抽象化两个概念:显示对象列表和显示某类型对象的详细页面。

    • 各汎用ビューは自分がどのモデルに対して動作するのかを知っておく必要がある。こではmodel属性を使用して提供される。

 

    DetailView汎用ビューには”pk”という名前でURLからプライマリーをキャプチャして渡すことになっている。

详细资料

默认情况下,DetailView通用视图使用名为/_detail.html的模板。
使用temple_name属性可以告诉Django使用指定的模板名,而不是自动生成的默认模板名。

列表视图

ListView通用视图使用默认模板/_list.html,因此可以使用template_name告诉ListView使用现有的”polls/index.html”模板。

请引用下列内容:

1. 请参考以下内容。
2. 即使只需要一种选择,也请参考下列文本。
3. 请参考下述内容。
4. 以下资料供参考。

请考虑以上表述,祝你使用愉快!

    • はじめての Django アプリ作成、その 1 | Django ドキュメント | Django

 

    • はじめての Django アプリ作成、その2 | Django ドキュメント | Django

 

    • はじめての Django アプリ作成、その 3 | Django ドキュメント | Django

 

    はじめての Django アプリ作成、その 4 | Django ドキュメント | Django
bannerAds