Django與mysql資料庫的串連

來源:互聯網
上載者:User

標籤:return   一個   nis   配置   .com   html   工程   環境   技術分享   

環境:win7+py3.4+mysql+pymysql

(以下預設工程和應用已經建立)

1.-->工程/settings.py    (資料庫配置)

DATABASES = {    ‘default‘: {        ‘ENGINE‘: ‘django.db.backends.mysql‘,        ‘HOST‘:‘127.0.0.1‘,        ‘PORT‘:3306,        ‘NAME‘: ‘bole‘,        ‘USER‘:‘root‘,        ‘PASSWORD‘:‘root‘,    }}

2.-->應用/models.py  (資料庫欄位設定)

from django.db import modelsclass python(models.Model):    title = models.CharField(max_length=20)    intro = models.CharField(max_length=100)    def __str__(self):        return self.title

3.-->遷移資料庫python manage.py makemigrations   +  python manage.py migrate

在Mysql資料庫中顯示

插入測試資料  : python manage.py shell   ------->>>from 應用.models import python       >>>c = python(title=‘test‘,intro=‘這是個測試‘)   >>>c.save()  .......

4.-->應用/views.py (編寫視圖函數顯示資料)

from django.shortcuts import renderfrom .models import pythondef index(request):    context = python.objects.all()    return render(request,‘index.html‘,context={‘context‘:context})

5.-->應用、工程/urls.py   (設定訪問路徑與視圖函數的映射)

應用/urls.py

from django.conf.urls import urlfrom . import viewsurlpatterns = [    url(r‘^index/$‘,views.index,name = ‘index‘),]

project/urls.py

from django.conf.urls import url,includefrom django.contrib import adminurlpatterns = [    url(r‘‘,include(‘DB.urls‘)),    url(r‘^admin/‘, admin.site.urls),]

6.-->index.html    (編寫最上層顯示模板)

settings.py 中修改

‘DIRS‘: [os.path.join(BASE_DIR,‘templates‘)],

在根目錄(manage.py所在目錄)建立templates檔案夾,在其中建立index.html

<ul>    {% for article in context %}    <li>        標題:{{article.title}}        內容:{{article.intro}}    </li>    {% endfor %}</ul>

至此涉及到的M(models)V(views)T(templates)都已完成,python manage.py runserver 在本機運行  http://127.0.0.1:8000/index/

運行另外的py程式修改該資料庫內容,重新整理後可更新內容

import pymysqltry:    con = pymysql.connect(host = ‘127.0.0.1‘,user = ‘root‘,passwd=‘root‘,charset=‘utf8‘)    con.query(‘create database bole‘)    con = pymysql.connect(host = ‘127.0.0.1‘,user = ‘root‘,passwd=‘root‘,db = ‘bole‘,charset=‘utf8‘)except:    con = pymysql.connect(host = ‘127.0.0.1‘,user = ‘root‘,passwd=‘root‘,db = ‘bole‘,charset=‘utf8‘)try:    passexcept:    print(‘Table existed‘)print(‘Finished‘)sql = "insert INTO db_python(title,intro) VALUES (‘test4‘,‘這還是一個即時測試‘)"con.query(sql)

-------------------By:羽凡     At:2017-10-6-23:55------------------

 

Django與mysql資料庫的串連

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.