在settings.py中保存了数据库的连接配置信息,Django默认初始配置使用sqlite数据库。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
使用MySQL数据库首先需要安装驱动程序
pip install PyMySQL
在Django的工程同名子目录的__init__.py文件中添加如下语句
import pymysql
pymysql.install_as_MySQLdb()
作用是让Django的ORM能以mysqldb的方式来调用PyMySQL。
修改DATABASES配置信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'mysql', # 数据库用户密码
'NAME': 'book' # 数据库名字
}
}
from django.db import models
# Create your models here.
class User(models.Model):
uid = models.CharField(primary_key=True, max_length=30)
homeurl = models.CharField(max_length=45)
sumvisit = models.IntegerField()
credit = models.IntegerField()
grade = models.IntegerField()
rank = models.IntegerField()
fans = models.IntegerField()
original = models.IntegerField()
reprint = models.IntegerField()
trans = models.IntegerField()
comment = models.IntegerField()
blogcnt = models.IntegerField()
# 在Python2中用__unicode__代替__str__
def __str__(self):
return self.uid
class Blog(models.Model):
uid = models.CharField(max_length=30)
title = models.CharField(max_length=200)
url = models.CharField(primary_key=True, max_length=30, null=False)
viewcnt = models.IntegerField()
# 在Python2中用__unicode__代替__str__
def __str__(self):
return self.title
#业务逻辑层
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
#注:每个响应对应一个函数,函数必须返回一个响应
from blog import models
def blogs(request):
# return HttpResponse("Hello world ! ")
# article = models.Blog.objects.get(pk='41078855')
# return render(request, 'blog/index.html', {"article": articles})
#获取全部博客信息
articles = models.Blog.objects.all()
#返回至前端渲染
return render_to_response("blog/index.html",locals()) #必须用这个return
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSDN</title>
</head>
<body>
<!--<h1>{{ article.title }}</h1>-->
<!--<h3>{{ article.viewcnt }}</h3>-->
<body>
<p>博文信息</p>
{% for article in articles %}
<p>{{article.title}}   :   {{article.viewcnt}}</p>
<br>
{% endfor %}
</body>
</body>
</html>