Django开发的简易留言板案例详解


Posted in Python onDecember 04, 2018

本文实例讲述了Django开发的简易留言板。分享给大家供大家参考,具体如下:

Django在线留言板小练习

环境

ubuntu16.04 + python3 + django1.11

1、创建项目

django-admin.py startproject message

进入项目message

2、创建APP

python manager.py startapp guestbook

项目结构

.
├── guestbook
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── message
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   └── settings.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

4 directories, 14 files

需要做的事:

配置项目setting 、初始化数据库、配置url 、编写views 、创建HTML文件

项目配置

打开message/settings.py

设置哪些主机可以访问,*代表所有主机

ALLOWED_HOSTS = ["*"]
INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'guestbook',  #刚刚创建的APP,加入到此项目中
]
#数据库默认用sqlite3,后期可以换成MySQL或者SQL Server等
TIME_ZONE = 'PRC' #时区设置为中国

创建数据库字段

#encoding: utf-8
from django.db import models
class Message(models.Model):
  username=models.CharField(max_length=256)
  title=models.CharField(max_length=512)
  content=models.TextField(max_length=256)
  publish=models.DateTimeField()
  #为了显示
  def __str__(self):
    tpl = '<Message:[username={username}, title={title}, content={content}, publish={publish}]>'
    return tpl.format(username=self.username, title=self.title, content=self.content, publish=self.publish)

初始化数据库

# 1. 创建更改的文件
root@python:/online/message# python3 manage.py makemigrations
Migrations for 'guestbook':
 guestbook/migrations/0001_initial.py
  - Create model Message
# 2. 将生成的py文件应用到数据库
root@python:/online/message# python3 manage.py migrate
Operations to perform:
 Apply all migrations: admin, auth, contenttypes, guestbook, sessions
Running migrations:
 Applying contenttypes.0001_initial... OK
 Applying auth.0001_initial... OK
 Applying admin.0001_initial... OK
 Applying admin.0002_logentry_remove_auto_add... OK
 Applying contenttypes.0002_remove_content_type_name... OK
 Applying auth.0002_alter_permission_name_max_length... OK
 Applying auth.0003_alter_user_email_max_length... OK
 Applying auth.0004_alter_user_username_opts... OK
 Applying auth.0005_alter_user_last_login_null... OK
 Applying auth.0006_require_contenttypes_0002... OK
 Applying auth.0007_alter_validators_add_error_messages... OK
 Applying auth.0008_alter_user_username_max_length... OK
 Applying guestbook.0001_initial... OK
 Applying sessions.0001_initial... OK

配置url

设置项目message/urls.py

from django.conf.urls import url,include #添加了include
from django.contrib import admin
urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^guestbook/', include('guestbook.urls',namespace='guestbook')),  #表示在url地址中所有guestbook的都交给guestbook下面的url来处理,后面的逗号不要省略
]

设置APP的url

如果是初次创建APP,urls.py在APP中一般不存在,创建即可

vim guestbook/urls.py

# 内容如下
from django.conf.urls import url
from . import views
urlpatterns = [
  url(r'^index/',views.index,name='index'),  #不要忘了逗号
]

编写views

编辑APP中的views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from . import models
# Create your views here.
def index(request):
  messages = models.Message.objects.all()
  return render(request, 'guestbook/index.html', {'messages' : messages})

编写HTML文件

创建APP/templates/guestbook/index.html目录及文件

使用bootstrap美化了

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>留言板</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" crossorigin="anonymous">
  </head>
  <body>
    <table class="table table-striped table-bordered table-hover table-condensed">
      <thead>
        <tr class="danger">
          <th>留言时间</th>
          <th>留言者</th>
          <th>标题</th>
          <th>内容</th>
        </tr>
      </thead>
      <tbody>
        {% if messages %}
          {% for message in messages %}
            <tr class="{% cycle 'active' 'success' 'warning' 'info' %}">
              <td>{{ message.publish|date:'Y-m-d H:i:s' }}</td>
              <td>{{ message.username }}</td>
              <td>{{ message.title }}</td>
              <td>{{ message.content }}</td>
            </tr>
          {% endfor %}
        {% else %}
          <tr>
            <td colspan="4">无数据</td>
          </tr>
        {% endif %}
      </tbody>
    </table> 
    <a class="btn btn-xs btn-info" href="/guestbook/create/" rel="external nofollow" >去留言</a>
  </body>
</html>

调试index页面

python manage.py runserver 0.0.0.0:99

打开浏览器访问http://开发机器ip地址:99/guestbook/index/

Django开发的简易留言板案例详解

留言展示页面成功

创建留言页面

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>留言</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" crossorigin="anonymous">
  </head>
  <body>
    <!-- 我是注释 -->
    <h3>留言</h3> <!--h1-> h6-->
    <!--method: POST /GET -->
    <form action="/guestbook/save/" method="POST" novalidate="novalidate">
    {% csrf_token %}
      <table class="table table-striped table-bordered table-hover table-condensed">
        <label>用户名:</label> <input type="text" name="username" placeholder="用户名" /> <br /><br />
        <label>标 题:</label> <input type="text" name="title" placeholder="标题" /><br /><br />
        <label>内 容:</label> <textarea name="content" placeholder="内容"> </textarea><br /><br />
      </table>
      <input class="btn btn-success" type="submit" value="留言"/>
    </form>
  </body>
</html>

配置APP下的url

vim guestbook/urls.py

urlpatterns = [
  url(r'^index/',views.index,name='index'),  #不要忘了逗号
  url(r'^create/$', views.create, name='create'),
  url(r'^save/$', views.save, name='save'), 
]

编辑views.py

#先导入时间模块
import datetime
#添加create、save
def create(request):
  return render(request, 'guestbook/create.html')
def save(request):
  username = request.POST.get("username")
  title = request.POST.get("title")
  content = request.POST.get("content")
  publish = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  message = models.Message(title=title, content=content, username=username, publish=publish)
  message.save()
  return HttpResponseRedirect('/guestbook/index/')

OK,再次运行,enjoy it!

Django开发的简易留言板案例详解

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

Python 相关文章推荐
Python中变量交换的例子
Aug 25 Python
web.py在模板中输出美元符号的方法
Aug 26 Python
讲解Python中if语句的嵌套用法
May 14 Python
python语言使用技巧分享
May 31 Python
深入理解Python中的内置常量
May 20 Python
分享Pycharm中一些不为人知的技巧
Apr 03 Python
PyQt5 多窗口连接实例
Jun 19 Python
Python re正则表达式元字符分组()用法分享
Feb 10 Python
python中return不返回值的问题解析
Jul 22 Python
详解python datetime模块
Aug 17 Python
BeautifulSoup中find和find_all的使用详解
Dec 07 Python
Python环境搭建过程从安装到Hello World
Feb 05 Python
对python的bytes类型数据split分割切片方法
Dec 04 #Python
Python 从相对路径下import的方法
Dec 04 #Python
浅谈python中str字符串和unicode对象字符串的拼接问题
Dec 04 #Python
Python推导式简单示例【列表推导式、字典推导式与集合推导式】
Dec 04 #Python
对web.py设置favicon.ico的方法详解
Dec 04 #Python
对python 命令的-u参数详解
Dec 03 #Python
python 接收处理外带的参数方法
Dec 03 #Python
You might like
shopex中集成的站长统计功能的代码简单分析
2011/08/11 PHP
PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]
2011/12/16 PHP
php实现微信公众号无限群发
2015/10/11 PHP
php实现登陆模块功能示例
2016/10/20 PHP
PHP基于双向链表与排序操作实现的会员排名功能示例
2017/12/26 PHP
PHP使用ajax的post方式下载excel文件简单示例
2019/08/06 PHP
JScript中使用ADODB.Stream判断文件编码的代码
2008/06/09 Javascript
通过Javascript读取本地Excel文件内容的代码示例
2014/04/08 Javascript
jquery实现类似EasyUI的页面布局可改变左右的宽度
2020/09/12 Javascript
jQuery中mouseover事件用法实例
2014/12/26 Javascript
微信中一些常用的js方法汇总
2015/03/12 Javascript
jquery滚动特效集锦
2015/06/03 Javascript
使用CDN和AJAX加速WordPress中jQuery的加载
2015/12/05 Javascript
Javascript基于AJAX回调函数传递参数实例分析
2015/12/15 Javascript
JS产生随机数的几个用法详解
2016/06/22 Javascript
domReady的实现案例
2016/11/23 Javascript
JavaScript实现时钟滴答声效果
2017/01/29 Javascript
vue使用jsonp抓取qq音乐数据的方法
2018/06/21 Javascript
Vue 组件注册实例详解
2019/02/23 Javascript
JS实现图片切换特效
2019/12/23 Javascript
解决vue-router 切换tab标签关闭时缓存问题
2020/07/22 Javascript
js+css3实现简单时钟特效
2020/09/13 Javascript
Openlayers实现距离面积测量
2020/09/28 Javascript
python从sqlite读取并显示数据的方法
2015/05/08 Python
Python内建模块struct实例详解
2018/02/02 Python
python flask框架实现重定向功能示例
2019/07/02 Python
详解Python高阶函数
2020/08/15 Python
Python list和str互转的实现示例
2020/11/16 Python
英国网上花店:Bunches
2016/11/29 全球购物
Hertz荷兰:荷兰和全球租车
2018/01/07 全球购物
Haggar官网:美国男装品牌
2020/02/16 全球购物
生物医学工程专业学生求职信范文分享
2013/12/14 职场文书
党校培训思想汇报
2013/12/30 职场文书
开朗女孩的自我评价
2014/02/10 职场文书
Pandas 数据编码的十种方法
2022/04/20 Python
python神经网络Xception模型
2022/05/06 Python