用 Django2.0 做 简单的BBS(前端用 Bootstrap)

实现目标:

开发首页显示BBS的标题和摘要,点击BBS的标题可跳转到BBS详细页面进行展示。

开发环境及开发工具:

Python 3.6.3

Django 2.0

Pycharm 2017.3

实现过程:

1创建project

用语句创建:

django-admin startproject BBS_Pro

 

2、创建app

python manage.py startapp app01

3、启动服务

python manage.py runserver

4、编辑BBS_Pro/settings

把新创建的app名称加入,进行admin汉化:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]

LANGUAGE_CODE = 'zh-hans'  #修改

5、定义数据模型

编辑mblog/models.py

from django.db import models
from django.contrib.auth.models import User  #导入django自带的用户
class BBS(models.Model):  #BBS
    title = models.CharField(max_length=50)  #标题
    summary = models.CharField(max_length=200,blank=True,null=True)  #摘要。可以为空,blank是admin中可为空,null是表里可为空
    content = models.TextField()  #内容
    author = models.ForeignKey( 'BBS_user',on_delete=models.CASCADE,)  #作者,外键到BBS_user中,用到还未定义的表要用引号
    view_count = models.IntegerField() #浏览次数
    ranking = models.IntegerField() #排名
    created_at = models.DateTimeField()  #创建时间
    update_at = models.DateTimeField()  #更新时间
    def __str__(self):
        return self.title

class Category(models.Model):  #板块
    name = models.CharField(max_length=30,unique=True)  #板块名称,unique是不能重复
    administrator = models.ForeignKey('BBS_user',on_delete=models.CASCADE,)   #版主
    def __str__(self):
        return self.name

class BBS_user(models.Model):    #用户表。继承django自带的用户认证系统
    user = models.OneToOneField(User,on_delete=models.CASCADE,)   #用户
    signature = models.CharField(max_length=100,default='这家伙没有签名')   #签名
    photo = models.ImageField(upload_to="upload_imgs/", default="upload_imgs/user_1.jpg") #头像默认一个图片,upload_to会自动在根目录创建一个文件夹,支持上传
    def __str__(self):
        return self.user.username

6、生成数据表

python manage.py makemigrations app01

python manage.py migrate

7、生成admin的超级管理员

python manage.py createsuperuser

8、修改mblog/admin.py内容

from django.contrib import admin
from app01 import models

class BBS_admin(admin.ModelAdmin):
    list_display = ('title','summary','author','view_count','ranking','created_at','update_at')
    #上面一行作用是在admin中显示需要显示的字段
    list_filter = ('created_at',)    #是一个元组,末尾要加逗号
    search_fields = ('title','summary','author__user__username')
    #在admin中创建搜索,如果是外键的字段则用'auther__user__username'形式,此处要主要。

admin.site.register(models.BBS,BBS_admin)
admin.site.register(models.Category)
admin.site.register(models.BBS_user)

登录admin  127.0.0.1:8000/admin

9、创建模板和静态文件的文件夹

创建文件夹BBS_Pro/app01/templates/app01  这里放app01的所有模板;创建文件夹BBS_Pro/statics 这里放所有用到的静态文件。

Settings中增加内容:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "statics"),
]

Settings中修改TEMPLATES 的DIRS内容

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

10、创建文件app01/urls.py

from django.urls import path,include
from app01 import views
urlpatterns = [
    path('',views.index,name='index'),
]

11、修改BBS_Pro/urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('bbs/',include('app01.urls')),
]

12、修改app01/views.py内容

from django.shortcuts import render
from .models import BBS
def index(request):
    bbs_lists =BBS.objects.all()
    return render(request,'app01/index.html',{'bbs_lists':bbs_lists})

13、创建共享模版BBS_Pro/templates/base.html

Base.html可用bootstrap里面的模板修改,在需要的区域进行如下标记,便于其他模板补充

{% block page_content %}
{% endblock %}

具体页面代码如下:

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="/static/image/favicon.ico">
    <title>页面头名称</title>
    <!-- Bootstrap core CSS -->
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="navbar.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <!-- Static navbar -->
      <nav class="navbar navbar-default">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">项目测试名称</a>
          </div>
          <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
              <li class="active"><a href="#">全部</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                  <li class="dropdown">
                      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">列表 <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li role="separator" class="divider"></li>
                  <li class="dropdown-header">Nav header</li>
                  <li><a href="#">Separated link</a></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
            </ul>
          </div><!--/.nav-collapse -->
        </div><!--/.container-fluid -->
      </nav>
      <!-- Main component for a primary marketing message or call to action -->
      <div class="jumbotron">
        {% block page_content %}
      {% endblock %}
      </div>
    </div> <!-- /container -->
    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="/static/js/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="/static/js/bootstrap.min.js"></script>
  </body>
</html>

14、新增模板index.html

app01/templates/app01/index.html

{% extends 'base.html' %}

{% block page_content %}
    {% for bbs_list in bbs_lists %}
        <h4><a href="#">{{ bbs_list.title }}</a></h4>
        <h5>{{ bbs_list.summary}}</h5>
        <hr>
    {% endfor %}
{% endblock %}

15、修改views.py

定义index

from django.shortcuts import render
from .models import BBS
def index(request):
    bbs_lists =BBS.objects.all()
    return render(request,'app01/index.html',{'bbs_lists':bbs_lists})

16、查看效果 127.0.0.1/bbs

通过127.0.0.1/admin手工添加一些后台数据。

 

17、做bbs的详细页面

修改app01/urls.py内容,增加url:

path('<int:bbs_id>/',views.bbs_detail,name='bbs_detail'),

18、修改views.py

定义bbs_detail

def bbs_detail(request,bbs_id):    #传的参数给url用
    bbss =BBS.objects.get(id=bbs_id)
    return render(request,'app01/detail.html',{'bbs_obj':bbss})    #字典给模板用

19、新建模板detail.html

app01/templates/app01/detail.html

{% extends 'base.html' %}

{% block page_content %}
        <h4>{{ bbs_obj.title }}</h4>
        <h5>{{ bbs_obj.summary}}</h5>
        <h5>{{ bbs_obj.content}}</h5>
        <h5>{{ bbs_obj.author}}</h5>
        <h5>{{ bbs_obj.view_count}}</h5>
        <h5>{{ bbs_obj.ranking}}</h5>
        <h5>{{ bbs_obj.created_at}}</h5>
        <h5>{{ bbs_obj.update_at}}</h5>
        <hr>
{% endblock %}

20、修改index.html中的链接

{% extends 'base.html' %}

{% block page_content %}
    {% for bbs_list in bbs_lists %}
        <h4><a href="/bbs/{{bbs_list.id}}">{{ bbs_list.title }}</a></h4>
        <h5>{{ bbs_list.summary}}</h5>
        <hr>
    {% endfor %}
{% endblock %}

首页中点击bbs标题可链接进入bbs的详细内容页面。

 

posted @ 2017-12-22 12:56  summyfly  阅读(2559)  评论(1编辑  收藏  举报