新建一个django项目:
如下图,
添加项目目录文件:test_db,(如果文件不存在,会在该目录下新建一个文件夹)
设置app名称:testdb,在新的窗口打开项目,如图所示
其中,MVC模式中,models.py用于处理M,views.py用于处理V,urls.py用于映射视图。
1.下载pymysql:pip install pymysql
2.在项目__init__.py里添加(不是):
import pymysqlpymysql.install_as_MySQLdb()如图所示:
models.py中定义数据库表的字段:
from django.db import models
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __unicode__(self): return self.name在mysql中事先建立一个数据库,比如:book,然后修改setting.py中DATABASE如下:
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘:‘book‘, ‘USER‘:‘root‘, ‘PASSWORD‘:‘lyf123‘, ‘HOST‘:‘127.0.0.1‘, ‘POST‘:‘3306‘, # ‘ENGINE‘: ‘django.db.backends.sqlite3‘, #‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘), }}经过以上两个步骤,然后通过命令查看models.py对应的sql语句,命令如下:python manage.py sqlall testdb(项目名)(如果出现:App ‘testdb‘ has migrations的错误,只要将migrations文件删除即可),如下图所示:
然后通过命令python manage.py syncdb同步数据库,创建表,结果如下图:
启动mysql,输入对应的命令查看是否建立了该表和对应的字段。在views.py中添加视图处理:
from .models import Publisherfrom django.shortcuts import render_to_responsedef book_list(request): names = Publisher.objects.all() return render_to_response(‘book_list.html‘, {‘names‘: names})在urls.py中添加url映射:
url(r‘^book/‘,views.book_list),在templates中加入两个html文件:#base.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title> {% block title %}{% endblock %} </title></head><body> <h1>My book Site</h1> <hr> {% block content %}{% endblock %} {% block footer %} <p>Thanks for visiting my site.</p> {% endblock %}</body></html> #book_list.html
{% extends ‘base.html‘ %}{% block title %}title: book_lib{% endblock %}{% block content %}<table> <tr><th>name</th><th>address</th><th>city</th<th>country</th><th>website</th></tr> {% for m in names %} <tr> <td > {{ m.name }} </td> <td > {{ m.address }} </td> <td > {{ m.city }} </td> <td>{{m.country }}</td> <td>{{ m.website }}</td> </tr> {% endfor %} </table> {% endblock %}
运行django server,结果如下:
PS:表中的数据是通过mysql命令窗口自己胡乱写进去,用于测试的总结:这个例子是对django框架原理比较直观,简单的记录,还未涉及到对数据库进行增,删,改,查的操作
时间: 2024-10-07 11:30:20