### 第一步:定义模型
在项目(Blog)下的model.py中
~~~
class Banner(models.Model):
title=models.CharField('标题',max_length=50)
pic=models.ImageField('轮播图',upload_to='static/images/banner')
link_url=models.URLField('图片连接',max_length=100)
idx=models.IntegerField('索引排序')
is_active=models.BooleanField('是否是active',default=False)
create_time=models.DateTimeField('创建时间',default=datetime.now)
def __str__(self):
return self.title
class Meta:
verbose_name='轮播图'
verbose_name_plural='轮播图'
~~~
### 第二步:添加模型到settings.py中的INSTALLED_APPS中
比如下面的blogs就是我们添加进去的:
~~~
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogs',
]
~~~
### 第三步:生成模型内容
在命令提示符下,定位到manage.py目录中,然后输入
~~~
python manage.py makemigrations
~~~
如果出现下面的错误,说明没有安装ImageField所必须的第三方库
~~~
ERRORS:
blogs.Banner.pic: (fields.E210) Cannot use ImageField because Pillow is not installed.
HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".
WARNINGS:
?: (2_0.W001) Your URL pattern '^index/$' [name='index'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path().
~~~
**如何安装第三方库**
可以利用豆瓣的源来快速安装,不然国外的速度太慢
~~~
pip install --trusted-host pypi.douban.com -i http://pypi.douban.com/simple/ Pillow
~~~
### **第四步:生成数据库表**
在命令提示符中,执行
~~~
python manage.py migrate
~~~
### **第五步:创建模版文件夹templates和静态资源文件夹static,这两个文件夹与manage.py位于同一根目录下。并把静态资源css、js、images等静态资源放于static文件夹下面**
### **第六步:在settings.py中设置模板文件夹及静态文件夹**
模板的代码如下
~~~
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'template')],
'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',
],
},
},
]
~~~
静态文件的代码如下:
~~~
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,"static"),
)
~~~
### **第七步:创建首页,在blogs文件夹下的views.py中,写入**
~~~
def index(request):
return render(request,'index.html',{})
~~~
### **第八步:在urls.py中设置页面路径**
~~~
from blogs.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('blogs.urls')),
]
~~~
同时,在blogs下面新建一个urls.py的文件,并写入
~~~
from django.urls import path
from blogs.views import index
urlpatterns=[
path('',index,name='index'),
]
~~~
### **第九步:注册后台功能模块,实现可通过后台上传轮播图**
打开项目下面的admin.py,然后输入
~~~
from django.contrib import admin
from blogs.models import Banner
admin.site.register(Banner)
~~~
然后就可以进入后台进行添加轮播图了
### **第十步:动态查询轮播图数据**
打开blogs下面的views.py,并修改为
~~~
from django.shortcuts import render
from .models import Banner
# Create your views here.
def index(request):
banner_list=Banner.objects.all()
ctx={
'banner_list':banner_list
}
return render(request,'index.html',ctx)
~~~
第十一步:给静态页面赋值
打开templates下面的index.html
并修改为
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>博客首页</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/nifty.min.css" rel="stylesheet">
<script src="/static/js/jquery-2.2.4.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/nifty.min.js"></script>
</head>
<body>
<div id="banners" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators out">
{% for v in banner_list %}
{% if v.is_active %}
<li class="active" data-slide-to="{{v.idx}}" data-target="#banners"></li>
{% else %}
<li data-slide-to="{{v.idx}}" data-target="#banners" class=""></li>
{% endif %}
{% endfor %}
</ol>
<div class="carousel-inner text-center">
{% for v in banner_list %}
{% if v.is_active %}
<div class="item active">
<a href="{{v.link_url}}">
<img src="{{v.pic}}" alt="{{v.title}}" class="img-responsive" />
</a>
</div>
{% else %}
<div class="item">
<a href="{{v.link_url}}">
<img src="{{v.pic}}" alt="{{v.title}}" class="img-responsive" />
</a>
</div>
{% endif %}
{% endfor %}
<div class="item active">
<img src="" alt="" class="img-responsive" />
</div>
</div>
<a class="carousel-control left" data-slide="prev" href="#banners"><i class="demo-pli-arrow-left icon-2x"></i></a>
<a class="carousel-control right" data-slide="next" href="#banners"><i class="demo-pli-arrow-right icon-2x"></i></a>
</div>
</body>
</html>
~~~