Django练习

实现功能:

登录功能
添加功能
删除功能(未实现)

代码:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/commons.css" />
</head>
<body>
    <h1>欢迎登录</h1>
{#    <img src="/static/1.png">#}
    <h3>添加内容</h3>
    <form action="/index/" method="POST">
        <input type="text" placeholder="主机" name="host" />
        <input type="text" placeholder="端口" name="port" />
        <input type="submit" value="增加" />
    </form>

    <h3>资产列表</h3>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>端口</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for row in data %}
                <tr>
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.port }}</td>
                    <td><a href="/delete/?h={{ row.hostname }}">删除</a></td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login/" method="POST">
    <p>用户名<input type="text" name="user" /></p>
    <p>密码<input type="text" name="pwd" /></p>
    <input type="submit" value="提交" />

</form>
</body>
</html>

views.py

from django.shortcuts import render,HttpResponse,redirect
# from django.shortcuts import HttpResponse

# Create your views here.
#至少一个参数request
#request封装用户请求相关信息

DB=[
    {'hostname':'c1.com','port':80},
    {'hostname':'c2.com','port':80},
    {'hostname':'c3.com','port':80},
    {'hostname':'c4.com','port':80},
    {'hostname':'c5.com','port':80},
    {'hostname':'c6.com','port':80},
]

def index(request):
    # print(request.GET)
    #return HttpResponse('<h1 style="color:red;">OK</h1>')
    if request.method == "GET":
        #获取数据pymysql
        #模块渲染
        """
        1、读取html文件内容
        NB.将特殊的标记和{'data':DB}进入渲染,得到一个字符串
        2、将html内容返回给用户
        """
        return render(request,'index.html',{'data': DB})
    if request.method == 'POST':
        host = request.POST.get('host')
        port = request.POST.get('port')
        #拿到数据加到字典里面去
        temp = {'hostname': host,'port':port}
        DB.append(temp)
        # return render(request, 'index.html',{'data': DB})
        return redirect('/index/')

def login(request):
    #request.method "GET"  "POST"
    if request.method == 'GET':
        #request.GET.get()
        return render(request,'login.html')
    elif request.method == 'POST':
     # 获取用户提交的数据(POST)
        username = request.POST.get('user')
        password = request.POST.get('pwd')
        if username == 'root' and password == '123':
            # return redirect('http://www.baidu.com')
            return redirect('/index/')
        else:
            return render(request,'login.html')

settings.py

"""
Django settings for cmdb project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/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.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'v5f(=a7$&q^tx55iu1p53jf(gi=oq9y&t07b+w6#f+6tx_ngif'

# 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',
    'monitor',
]

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 = 'cmdb.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        '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 = 'cmdb.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/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.10/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.10/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.10/howto/static-files/

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

urls.py

"""cmdb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/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 monitor import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),
]

运行效果:

 

posted @ 2017-03-06 15:26  努力哥  阅读(459)  评论(0编辑  收藏  举报