Django(简易)

##P ###创建django project 1.创建文件夹 2.cd到文件夹路径下面
C:\Users\Administrator>cd C:\Users\Administrator\Desktop\website
C:\Users\Administrator\Desktop\website>
3.执行django-admin创建叫做firstsite的站点
C:\Users\Administrator\Desktop\website>django-admin startproject firstsite
##A ###创建第一个app—站点的项目模块 1.在firstsite文件目录下操作
C:\Users\Administrator\Desktop\website>cd firstsite
C:\Users\Administrator\Desktop\website\firstsite>
2.创建app(会生成firstapp文件夹)
C:\Users\Administrator\Desktop\website\firstsite>python manage.py startapp first
app
3.在站点firstsite/settings.py中配置配置这个项目模块的名字firstapp
"""
Django settings for firstsite project.

Generated by 'django-admin startproject' using Django 1.11.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9#qhea8eja602fe)i1szt)n%luw6b4c-8$ymj9gq$n2_kduu^0'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'firstapp',#######新增的项目模块名#######
    ]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'firstsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'firstsite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
文件目录图: ![这里写图片描述](https://img-blog.csdn.net/20170519212149127?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvR2Vla0xlZWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast) ##D ###创建数据库database 1.创建数据库python manage.py migrate
C:\Users\Administrator\Desktop\website\firstsite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
2.运行服务器 执行python manage.py runserver
C:\Users\Administrator\Desktop\website\firstsite>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
May 19, 2017 - 21:29:34
Django version 1.11.1, using settings 'firstsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
文件结构如图: ![这里写图片描述](https://img-blog.csdn.net/20170519224131816?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvR2Vla0xlZWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast) ##M ###创建数据库中的表 1.在firstapp/models.py中创建firstapp项目的数据库模型
from django.db import models

# Create your models here.
class People(models.Model):
    name = models.CharField(null=True, blank=True, max_length=200)
    job = models.CharField(null=True, blank=True, max_length=200)
2.记录数据库模型的变动
C:\Users\Administrator\Desktop\website\firstsite>python manage.py makemigrations
Migrations for 'firstapp':
  firstapp\migrations\0001_initial.py
    - Create model People
3.合并到数据库
C:\Users\Administrator\Desktop\website\firstsite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, firstapp, sessions
Running migrations:
  Applying firstapp.0001_initial... OK
makemigrations和migrate的区别: python manage.py makemigrations 相当于在该app下建立migrations目录,并记录下你所有关于models.py的改动,比如0001_initial.py,但是这个改动还没有作用到数据库文件中。 在执行命令python manage.py migrate才将改动作用到数据库文件中,比如产生table之类。 ##V ###视图层面加载数据库 在firstapp/views.py引入数据库,实例化person
from django.shortcuts import render, HttpResponse #从shortcuts库中引入render,HttpResponse
from firstapp.models import People   #从model中引入数据库在views中使用
from django.template import Context, Template #从Template库引入Context(把数据库装载成模板)和Template()

# Create your views here.
def first_try(request):
    person = People(name="Spock", job="officer")
    ###见下文
##T ###引入Template库,渲染模板
###接上文
    html_string = '''
            <html>
                <head>
                    <meta charset="utf-8">
                    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.css" media="screen" title="no title">
                    <title>firstapp</title>
                </head>
                <body>
                    <h1 class="ui center aligned icon header">
                        <i class="hand spock icon"></i>
                        Hello, {{ person.name }}
                    </h1>
                </body>
            </html>
        '''
        t = Template(html_string) #字符串变成模板
        c = Context({'person':person})#字典形式:person变量值(后)传入person名的键(前)----前面的person对应的是模板中的person.name中的person
        web_page = t.render(c) #将c渲染到模板t中,用web_page储存
        return HttpResponse(web_page)
##U ###为视图文件中的函数配置url
"""firstsite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from firstapp.views import first_try#从视图文件中引入函数

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^first_try/', first_try),   #为视图文件中的函数first_try配置url【r'^first_try/'】
]
输入http://127.0.0.1:8000/first_try/显示网页。 而输入http://127.0.0.1:8000/显示图片为error

使用firstsite.urls中定义的URLconf,Django按照以下顺序尝试了这些URL模式:
^管理员/
^ first_try/
空路径与其中的任何一个都不匹配。
你看到这个错误,因为你的Django设置文件中有DEBUG = True。 将其更改为False,Django将显示标准的404页面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值