django 基本操作,猜数字,点击按钮跳转页面

views.py

from django.shortcuts import render
from django.http import HttpResponse
import random

# Create your views here.

numbers = random.randint(1, 101)


class People(object):
    def __init__(self, name, age, phone):
        self.name = name
        self.age = age
        self.phone = phone


def index(request):
    print(request)

    people = People('李四', 25, 1111)

    data = {
        'name': '张三',
        'age': 22,
        'numbers': [x for x in range(0, 30) if x % 2 == 0],
        'dictData': {'city': '郑州', 'weather': '晴天'},
        'people': people
    }
    return render(request, 'index.html', data)


def login(request):
    print(request)
    # 判断是get 请求 还是post 请求

    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        #
        #
        ID = request.POST.get('id', default='')
        pwd = request.POST.get('pwd', default='')
        if ID == '123456789' and pwd == '123456':
            return HttpResponse('登录成功')
        else:
            return render(request, 'login.html', {'error': '密码错误'})


# 定义主页的视图函数
def guess_num(request):
    result = ''
    # 判断当前请求的 是get /post
    # 设置全局变量
    global numbers
    if request.method == 'POST':
        # 从post 请求中提取传递过来的参数
        gus_num = request.POST.get('gus_num', default='0')
        if gus_num == '':
            result = '请重新输入,数字不能为空'
        else:
            if int(gus_num) < numbers:
                result = '猜小了'
            elif int(gus_num) > numbers:
                result = '猜大了'
            else:
                result = '猜对了,答案已重置,请继续'
                numbers = random.randint(0,101)
    names = ['小红', '小明', '小李', '小王', '小花']
    data = {
        'name': random.choice(names),
        'age': random.randint(18, 23),
        # 返回的是一个列表,startswith () 是以什么开头的
        'names': [name for name in names if name.startswith('小')],
        'phone': 13213,
        'result': result
    }
    # data 就是箱模板传递参数
    return render(request, 'guess_num.html', data)

settings.py

"""
Django settings for django_demo4 project.

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

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 = 'l&nmv@o_n_g3#k!0lf^0y#3qzb$j7-9hushlmdoup*erbnk1=c'

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

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 = 'django_demo4.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 = 'django_demo4.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/'

urls.py

"""django_demo4 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 app import views

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

guess_num.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>猜数字首页</title>
    <style>
        nav{
            text-align: center;
            color: mediumaquamarine;
            font-family: 楷体;
        }
        main{
            position: relative;
            width: 100%;
        }
        main>div{
            width: 600px;
            margin:0 auto;
            text-align: center;
        }
    </style>
</head>
<body>
    <nav>
        {# {{ 取传递过来的变量的值 }} #}
        <h3>欢迎{{ name }}来猜数字游戏</h3>
        <h3>年龄: {{ age }}</h3>
        <h3>电话: {{ phone }}</h3>
        {# 模板中的for循环 #}
        {% for name in names %}
            {# 取出列表中的每一个元素 #}
            <h3>{{ name }}</h3>
        {# endfor 表示for 循环结束 #}
        {% endfor %}
    </nav>
    <main>
        <div>
            {# action 表单提交的路由地址 method 指定提交的方式 默认get #}
            <form action="/guess/" method="post">
                {# csrf_token 提交token 验证 #}
                {% csrf_token %}
                {#  placeholder 占位字符 name 表单数据对应的key#}
                <input name="gus_num" type="text" placeholder="请输入你猜的数字"><br>
                <button type="submit">提交</button>
            </form>
            <h3>{{ result }}</h3>
        </div>
    </main>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板参数传递</title>
</head>
<body>

    <h1>{{ name }}</h1>
    <h1>{{ age }}</h1>
    {# for 循环遍历列表 ,取出每一个值 #}
    <ul>
        {# 每执行一次for循环,都会新建一个li标签 #}
        {% for num in numbers %}
        {#  每次for 循环,都会新建一个li标签 #}
             {#  forloop.counter(从1开始) counter0(从0开始) 记录循环的次数 .first判断是否为列表的第一个元素#}
            {# if 可以判断某些条件是否成立 #}
            {% if forloop.first %}
            <li>这是第一个元素</li>
            {% elif forloop.last %}
            <li>这是最后一个元素</li>
            {% else %}
            <li>{{ num }}</li>
            {% endif %}
            <li>{{ forloop.counter}}</li>
        {% endfor %}

    </ul>
    {#使用if 判断某个参数是否存在  #}
    {% if dictData %}
        <h1>dictData这个参数</h1>
        <h3>{{ dictData.city }}</h3>
        <h3>{{ dictData.weather }}</h3>
    {% else %}
        <h1>没有dictData这个参数</h1>

    {% endif %}
    {# 穿过来的是自定义对象,直接通过,属性获取属性值 #}
   <h1> {{poeple.name  }}</h1>
   <h1> {{people.age  }}</h1>
   <h1> {{people.phone  }}</h1>
    {# 填写要访问的路由 #}
    <a href="/login/">点击登录</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>银行卡登录页面</title>
</head>
<body>
    <div>填写完点击登录</div>
    <form action="/login/" method="post">
        {# csrf_token验证 #}
        {% csrf_token %}
        <input name="id" type="text" placeholder="请输入银行卡号">
        <input name="pwd" type="password" placeholder="请输入取款密码">
        <button type="submit">点击登录 </button>
        {% if error %}
            <h1>{{ error }}</h1>

        {% endif %}
    </form>
</body>
</html>

猜你喜欢

转载自my.oschina.net/u/3771014/blog/1796347