Django简单描述

文件目录

编写urls.py文件

编写views.py文件

from django.shortcuts import render
from django.shortcuts import HttpResponse

def index(request):
    return HttpResponse('hello,world!')

通过以上步骤我们就实现了访问index路径返回helloworld的功能,如果我们需要返回HTML文件,就需要将我们的文件放入templates中。现假定我们已经放入了需要的index.html文件,接下来需要重新编写我们的views.py文件。

from django.shortcuts import render

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

由于需要知道我们index.html的存放路径,所以可以在settings.py文件中进行添加

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],#设置html文件
        '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',
            ],
        },
    },
]

说完templates就一定要讲一下static了,这是静态文件的保存路径,需要用到的js,css均可放在这里。static配置也在settings文件中。

STATIC_URL = '/static/'#找到需要加载的各种css和js等插件

STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
    )

注册app,将app添加进列表即可

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first'#注册APP
]

连接数据库,同样也在settings中进行设置,默认使用的是sqllite,可以不用进行修改

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

使用mysql数据库进行配置

DATABASES = {
    'default': {
     'ENGINE': 'django.db.backends.mysql', #数据库引擎
     'NAME': 'web',                        #数据库名
     'USER': 'root',                       #用户名
     'PASSWORD': 'root',                   #密码
     'HOST': '127.0.0.1',                  #数据库主机,默认为localhost
     'PORT': '3306',                       #数据库端口,MySQL默认为3306
     'OPTIONS': {
           'autocommit': True,
         },
    }
}

编写models.py文件

以下是一个简单的输入信息方法

from django.db import models

class UserInfo(models.Model):
    user=models.CharField(max_length=32)
    passwd=models.CharField(max_length=32)