Django快速入门搭建网站

Django 最初被设计用于具有快速开发需求的新闻类站点,目的是要实现简单快捷的网站开发
编写Django应用文档

  • 1、安装 Django正式版

    • 安装Django:python -m pip install Django
    • 验证:python -m django --version 或者 print(django.get_version())
  • 2、创建项目

    • 在命令行中,cd 目录进入希望存储代码的目录,并创建一个新目录(如 djangotutorial ):mkdir djangotutorial

    • 新建一个名为 mysite 的Django项目:django-admin startproject mysite djangotutorial
      此时项目结构预期如下:

      text 复制代码
      djangotutorial/
          manage.py			-> 管理 Django 项目的命令行工具
          mysite/				-> 项目的实际 Python 包
              __init__.py		-> 标识 mysite 为 python 包的空文件
              settings.py		-> Django 项目的配置文件
              urls.py			-> Django 项目的 URL 声明
              asgi.py			-> 运行在 ASGI 兼容的 Web 服务器上的入口
              wsgi.py			-> 运行在 WSGI 兼容的Web服务器上的入口
  • 3、启动服务cd djangotutorial 进入项目目录下,运行python manage.py runserver

    • 为了使您的开发服务器对网络上的其他机器可见,运行:python manage.py runserver 0.0.0.0:8000
      还需要在 settings.py 中修改 ALLOWED_HOSTS 将本机IP地址添加进来比如:ALLOWED_HOSTS = ['10.225.1.1', '127.0.0.1', 'localhost']
  • 4、访问 :通过浏览器访问 http://127.0.0.1:8000/ 或其他人访问 http://10.225.1.1:8000/,服务器运行成功,你将看到一个"祝贺"页面,有一只火箭正在发射。

  • 5、项目配置好了,此时创建应用程序 ,比如名为 polls:python manage.py startapp polls,布局如下:

    text 复制代码
    polls/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py
  • 6、编写视图并配置

    • 打开 polls/views.py,输入如下内容:

      python 复制代码
      from django.http import HttpResponse
      
      
      def index(request):
          return HttpResponse("Hello, world. You're at the polls index.")
    • 要在浏览器中访问它,我们需要将其映射到一个 URL,为 polls 应用定义一个 URLconf,创建一个名为 polls/urls.py 的文件,写入如下内容:

      python 复制代码
      from django.urls import path
      
      from . import views
      
      urlpatterns = [
          path("", views.index, name="index"),
      ]
    • 在项目中定义polls的url配置,用 include 引用其他 URLconfs ,修改mysite/urls.py

      python 复制代码
      from django.contrib import admin
      from django.urls import include, path  # 导入include
      
      urlpatterns = [
          path("polls/", include("polls.urls")),  # 添加这一行声明
          path("admin/", admin.site.urls),
      ]
    • 重新启动服务,访问 http://localhost:8000/polls/ 验证改动。

views.py中的视图返回形式举例:

  • HttpResponse

    python 复制代码
    from django.http import HttpResponse
    import datetime
    
    
    def current_datetime(request):
        now = datetime.datetime.now()
        html = '<html lang="en"><body>It is now %s.</body></html>' % now
        return HttpResponse(html)
  • render返回自定义的HTML文件:

    python 复制代码
    from django.http import Http404
    from django.shortcuts import render
    from polls.models import Poll
    
    
    def detail(request, poll_id):
        try:
            p = Poll.objects.get(pk=poll_id)
        except Poll.DoesNotExist:
            raise Http404("Poll does not exist")
        return render(request, "polls/detail.html", {"poll": p})
  • render返回模板文件:

    python 复制代码
    from django.shortcuts import render
    
    # Create your views here.
    def index(request):
        return render(request, 'index.html')

    index.html 位于项目 djangotutorial 下的 templates 文件夹内时,修改settings配置:

    python 复制代码
    from pathlib import Path
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    INSTALLED_APPS = [
        ...,
        "polls",  # 应用名
        ...,
    ]
    
    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [BASE_DIR / "templates"],  # 添加模板目录
            "APP_DIRS": True,
            # ...
        },
    ]