zoukankan      html  css  js  c++  java
  • Django创建

    Pycharm里面Django模块安装及项目创建和启动:

    Pycharm里面Django模块安装(也可以指定安装源):

    创建Django项目:

    注意切换到合适的目录进行安装

    diango-admin stratproject myfirstDjango(项目名字)

    启动diango项目:

    方式一:

    命令行启动:

    python3 manage.py runserver (可以有下面三种写法)

    -python3-manage.py runserver 127.0.0.1:8002
    -python3-manage.py runserver 8002
    -python3-manage.py runserver

     方式二:

    pycharm启动:点击绿色箭头

    停止就是crl+c

    Django项目目录介绍:

    settings--django全局配置文件

    urls---路由关系

    settings文件里面的配置信息:

    DEBUG
    INSTALLED_APPS---》放app的名字
    MIDDLEWARE--》中间件
    TEMPLATES---》指定我模板文件放的路径
    DATABASES---》指定连接的数据库
    
    静态文件配置:(注意名字不能错)
    STATICFILES_DIRS=[
        os.path.join(BASE_DIR, 'static'),
    ]
    
    	    
    

    三件套:
    render 模板渲染
    HttpResponse 返回字符串
    redirect 重定向

    templates:html模板目录

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/css/mycss.css">
    </head>
    <body>
        <h1>Gjango-templates里面index.html</h1>
    </body>
    </html>
    index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录页面</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <!--<form action="http://127.0.0.1:8000/login_submit/" method="post"> 或者action="/login_submit"  -->
                    <!--action指定提交到哪个界面,method='post'指定用什么方式提交,一般有数据的用post-->
                    <!--设置为空表示就提交到当前界面-->
                    <form action="" method="post">
                        <p>用户名:<input type="text" name="name" class="form-control"></p>
                        <p>密码:<input type="password" name="password" class="form-control"></p>
                        <p ><input type="submit"  class="form-control" value="登录"></p>
                        <!--当用户密码错误时下面增加一条提示信息-->
                        <p class="text-danger text-center">{{ error }}</p>
    
                    </form>
    
                </div>
    
            </div>
    
        </div>
    </body>
    </html>
    login.html

    urls.py文件:

    """myfirstDjango 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 app01 import views
    
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),
        url(r'^login/', views.login),
        url(r'^login_submit/', views.login_submit),
    
    ]
    urls.py

    settings.py配置文件:

    """
    Django settings for myfirstDjango project.
    
    Generated by 'django-admin startproject' using Django 1.11.
    
    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 = 't83)1fjgh1a_mfm9**is^mjpaq0+ds^w4lgzjx0aw48!o1h53&'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    
    DEBUG = True  #测试阶段设置成为true,用于调试,上线后设置成false
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    #App建完之后需要手动添加到settings里面:
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        #2种添加方式推荐第二种方式添加
        # 'appp01',
        'app01.apps.App01Config',
    ]
    
    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 = 'myfirstDjango.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            #指定templates模板的路径
            'DIRS': [os.path.join(BASE_DIR,'templates')],
            '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 = 'myfirstDjango.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/'   #这个名字和static里面href="/static/css/mycss.css"是对应的(不一定要和目录文件夹名字一致)
    STATICFILES_DIRS=[
        #指定模板渲染用的文件和样式:例如图片、css、js、bootstrap
        os.path.join(BASE_DIR,'static'),   #要和右侧分类文件夹的名字一致
    ]
    settings.py

    views视图:

    from django.shortcuts import render,HttpResponse,redirect
    #render 模板渲染
    #HttpResponse 返回字符串
    # redirect 重定向
    
    import pymysql
    
    # Create your views here.
    
    def index(request):
        #request是请求体的一个对象,包含了行首、请求体内容,并且已经在内容进行了切分,
        print (request.method) #例如:结果就是GET
    
        #return HttpResponse(''<h1>Hellw</h1>'') #返回的东西都想响应体里面的
        return render(request,'index.html')  #对页面进行渲染替换并返回给web端(因为在templates里面添加了模板的路径所以直接访问)
    
    
    def login(request):
        error=''
        print(request.POST)
        if request.method == 'POST':
            name = request.POST['name']
            password = request.POST.get('password',None)
            conn = pymysql.connect(host='127.0.0.1',user='root',password='root',database='test',port=3306)
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            cursor.execute('select * from user where  name=%s and password=%s', [name, password])
            user = cursor.fetchone()
            if user:
                return HttpResponse('登录成功')
            else:
                error = '用户名密码错误'
            #render参数后面还可以跟个字典,回去找对应html文件里面对应的变量做渲染替换
        return render(request,'login.html',{'error':error})
    
    def login_submit(request):
        print(request.POST)
        #2种取值方式,推荐用用下那种
        name = request.POST['name']
        # 推荐用这种
        # request.POST  请求体的内容都在里面,字典形式
        # <QueryDict: {'name': ['123'], 'password': ['444']}>
        password = request.POST.get('password',None)
        if name == 'yangzhizong' and password =='123':
            #redirect重定向()
            return redirect('/index/')
        return redirect('/login/')
    views视图(响应体页面对象的函数)

    apps:

    from django.apps import AppConfig
    
    class App01Config(AppConfig):
        name = 'app01'
    apps.py

    安装apps:

    方式一:manage.py startapp app01(app项目的名字)

    方式二:

    orm:对象关系映射
    例如:
    python代码------》sql
    前端:
    $("#app")------>document.getEmlementById(‘app’)

    优点:
    1 sql掌握一般,也可开发程序
    2 开发效率高
    3 易用,学习曲线短

    缺点:
    1 sql大神,执行效率高,可能orm 执行效率低
    2 有的复杂的sql语句不能运行

  • 相关阅读:
    行列式的六条运算法则整理
    李昊大佬的CV模板
    洛谷P2918 [USACO08NOV]买干草(一道完全背包模板题)
    .
    洛谷P2822 组合数问题
    欧拉筛法模板&&P3383 【模板】线性筛素数
    拓展欧几里得算法
    欧几里得算法求最大公约数模板
    P2678 跳石头
    【五一qbxt】test1
  • 原文地址:https://www.cnblogs.com/yangzhizong/p/9550837.html
Copyright © 2011-2022 走看看