MySQL配置
pip3 install PyMySQL
# 在__init__.py添加如下内容:
import pymysql
pymysql.install_as_MySQLdb()
项目配置
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
# models.py
class Blog(models.Model):
title = models.CharField(max_length=50)
category = models.CharField(max_length=20, blank=True)
create_time = models.CharField(max_length=20)
content = models.TextField(blank=True, null=True)
# views.py
def home(request):
posts = Blog.objects.all()
paginator = Paginator(posts, 5)
page = request.GET.get('page')
try:
post_list = paginator.page(page)
except PageNotAnInteger:
post_list = paginator.page(1)
except EmptyPage:
post_list = paginator.paginator(paginator.num_pages)
return render(request, 'home2.html', {'post_list': post_list})
#urls.py
from app.views import home
urlpatterns = [
......
url(r'^home$', home, name='home'),
......
]
效果图如下(待完善...):
Github仓库:django-blog