经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Django » 查看文章
Django开发的简易留言板案例详解
来源:jb51  时间:2018/12/5 9:22:46  对本文有异议

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

Django在线留言板小练习

环境

ubuntu16.04 + python3 + django1.11

1、创建项目

  1. django-admin.py startproject message

进入项目message

2、创建APP

  1. 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

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

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

创建数据库字段

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

初始化数据库

  1. # 1. 创建更改的文件
  2. root@python:/online/message# python3 manage.py makemigrations
  3. Migrations for 'guestbook':
  4.  guestbook/migrations/0001_initial.py
  5.   - Create model Message
  6. # 2. 将生成的py文件应用到数据库
  7. root@python:/online/message# python3 manage.py migrate
  8. Operations to perform:
  9.  Apply all migrations: admin, auth, contenttypes, guestbook, sessions
  10. Running migrations:
  11.  Applying contenttypes.0001_initial... OK
  12.  Applying auth.0001_initial... OK
  13.  Applying admin.0001_initial... OK
  14.  Applying admin.0002_logentry_remove_auto_add... OK
  15.  Applying contenttypes.0002_remove_content_type_name... OK
  16.  Applying auth.0002_alter_permission_name_max_length... OK
  17.  Applying auth.0003_alter_user_email_max_length... OK
  18.  Applying auth.0004_alter_user_username_opts... OK
  19.  Applying auth.0005_alter_user_last_login_null... OK
  20.  Applying auth.0006_require_contenttypes_0002... OK
  21.  Applying auth.0007_alter_validators_add_error_messages... OK
  22.  Applying auth.0008_alter_user_username_max_length... OK
  23.  Applying guestbook.0001_initial... OK
  24.  Applying sessions.0001_initial... OK

配置url

设置项目message/urls.py

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

设置APP的url

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

vim guestbook/urls.py

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

编写views

编辑APP中的views.py

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

编写HTML文件

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

使用bootstrap美化了

  1. <!DOCTYPE html>
  2. <html>
  3.   <head>
  4.     <meta charset="utf-8" />
  5.     <title>留言板</title>
  6.     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" crossorigin="anonymous">
  7.   </head>
  8.   <body>
  9.     <table class="table table-striped table-bordered table-hover table-condensed">
  10.       <thead>
  11.         <tr class="danger">
  12.           <th>留言时间</th>
  13.           <th>留言者</th>
  14.           <th>标题</th>
  15.           <th>内容</th>
  16.         </tr>
  17.       </thead>
  18.       <tbody>
  19.         {% if messages %}
  20.           {% for message in messages %}
  21.             <tr class="{% cycle 'active' 'success' 'warning' 'info' %}">
  22.               <td>{{ message.publish|date:'Y-m-d H:i:s' }}</td>
  23.               <td>{{ message.username }}</td>
  24.               <td>{{ message.title }}</td>
  25.               <td>{{ message.content }}</td>
  26.             </tr>
  27.           {% endfor %}
  28.         {% else %}
  29.           <tr>
  30.             <td colspan="4">无数据</td>
  31.           </tr>
  32.         {% endif %}
  33.       </tbody>
  34.     </table> 
  35.     <a class="btn btn-xs btn-info" href="/guestbook/create/" rel="external nofollow" >去留言</a>
  36.   </body>
  37. </html>

调试index页面

  1. python manage.py runserver 0.0.0.0:99

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

留言展示页面成功

创建留言页面

  1. <!DOCTYPE html>
  2. <html>
  3.   <head>
  4.     <meta charset="utf-8" />
  5.     <title>留言</title>
  6.     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" crossorigin="anonymous">
  7.   </head>
  8.   <body>
  9.     <!-- 我是注释 -->
  10.     <h3>留言</h3> <!--h1-> h6-->
  11.     <!--method: POST /GET -->
  12.     <form action="/guestbook/save/" method="POST" novalidate="novalidate">
  13.     {% csrf_token %}
  14.       <table class="table table-striped table-bordered table-hover table-condensed">
  15.         <label>用户名:</label> <input type="text" name="username" placeholder="用户名" /> <br /><br />
  16.         <label>标 题:</label> <input type="text" name="title" placeholder="标题" /><br /><br />
  17.         <label>内 容:</label> <textarea name="content" placeholder="内容"> </textarea><br /><br />
  18.       </table>
  19.       <input class="btn btn-success" type="submit" value="留言"/>
  20.     </form>
  21.   </body>
  22. </html>

配置APP下的url

vim guestbook/urls.py

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

编辑views.py

  1. #先导入时间模块
  2. import datetime
  3. #添加create、save
  4. def create(request):
  5.   return render(request, 'guestbook/create.html')
  6. def save(request):
  7.   username = request.POST.get("username")
  8.   title = request.POST.get("title")
  9.   content = request.POST.get("content")
  10.   publish = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  11.   message = models.Message(title=title, content=content, username=username, publish=publish)
  12.   message.save()
  13.   return HttpResponseRedirect('/guestbook/index/')

OK,再次运行,enjoy it!

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号