python使用jdango建立web項目完整步驟__web

來源:互聯網
上載者:User

一、首先我們使用pycharm建立一個jdango項目

app名稱為jdango_Second,建立好的格式如圖所示:


二、我們建立的項目是MTV模式的

即model(對應資料庫),templates(頁面顯示),view(邏輯處理)

          models.py:

from django.db import models# Create your models here.class Stu(models.Model):    id = models.CharField(max_length=16,primary_key=True)    name=models.CharField(default='dqd',max_length=16)

views.py:

from django.shortcuts import renderfrom jdango_Second.models import Stu# Create your views here.def showInfo(request):    stu_list = Stu.objects.all()    content = {'list':stu_list}    return render(request,'index.html',content)

在admin.py將models.py中的類註冊:

from django.contrib import adminfrom jdango_Second.models import Stu# Register your models here.admin.site.register(Stu)


在項目的__init__.py我們可以做一些初始化(second):

import pymysqlpymysql.install_as_MySQLdb()db = pymysql.connect("localhost",'root','','py_second')cursor = db.cursor()cursor.execute('SELECT VERSION()')data = cursor.fetchone()print("Version is %s" % data)db.close()

同樣在項目的setting.py中我們設定連結的資料庫和制定靜態路徑和templates的路徑:

"""Django settings for second project.Generated by 'django-admin startproject' using Django 1.11.2.For more information on this file, seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full list of settings and their values, seehttps://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 = 'z=%7&(7pk#$)=2h+gs#kz9479#cvd1%1f#sd98nzz-#18ke0(2'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'jdango_Second.apps.JdangoSecondConfig',]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 = 'second.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 = 'second.wsgi.application'# Database# https://docs.djangoproject.com/en/1.11/ref/settings/#databasesDATABASES = {    #'default': {    #    'ENGINE': 'django.db.backends.sqlite3',    #    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),    #}    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'py_second',        'USER': 'root',        'PASSWORD': '',        'HOST': '127.0.0.1',        'port': '3306',    }}# Password validation# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/1.11/howto/static-files/STATIC_URL = '/static/'STATIC_PATH = os.path.join(BASE_DIR,'static')STATICFILES_DIRS = (    STATIC_PATH,)TEMPLATE_PATH = os.path.join(BASE_DIR,'templates')TEMPLATE_DIRS=[    TEMPLATE_PATH,]


項目的urls.py中配置瀏覽器地址欄的路徑和views.py中的函數名稱對應起來:

from django.conf.urls import urlfrom django.contrib import adminfrom jdango_Second.views import showInfourlpatterns = [    url(r'^admin/',admin.site.urls),    url(r'^index/',showInfo),]

static路徑下用於放置各種靜態檔案,如:

static

     img

          1.png

     js

     css



templates的路徑為:

templates

      index.html


index.html:

<!DOCTYPE html>{% load staticfiles %}<html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><image src="{% static 'img/1.jpg' %}"/><ul>    {%for item in list%}        <li>            {{ item.id }}            {{ item.name }}        </li>    {% endfor %}</ul></body></html>

三、建立 Django admin 使用者名稱和密碼:


初始化資料庫表


manage.py@HelloDj > makemigrations


manage.py@HelloDj > migrate


2.3 建立admin user

manage.py@HelloDj >createsuperuser



輸入使用者。。密碼。。 (參考:http://blog.csdn.net/wengyupeng/article/details/52266635)



四、開啟瀏覽器輸入localhost:8000/admin進入如下介面:


點擊Stus,進入增添資料即可,然後在在地址欄輸入localhost:8000/index就可以看到資料庫中取出的資料了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.