国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Django開(kāi)發(fā)的簡(jiǎn)易留言板案例詳解

2020-01-04 13:56:18
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Django開(kāi)發(fā)的簡(jiǎn)易留言板。分享給大家供大家參考,具體如下:

Django在線留言板小練習(xí)

環(huán)境

ubuntu16.04 + python3 + django1.11

1、創(chuàng)建項(xiàng)目

django-admin.py startproject message

進(jìn)入項(xiàng)目message

2、創(chuàng)建APP

python manager.py startapp guestbook

項(xiàng)目結(jié)構(gòu)

.
├── 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

需要做的事:

配置項(xiàng)目setting 、初始化數(shù)據(jù)庫(kù)、配置url 、編寫(xiě)views 、創(chuàng)建HTML文件

項(xiàng)目配置

打開(kāi)message/settings.py

設(shè)置哪些主機(jī)可以訪問(wèn),*代表所有主機(jī)

ALLOWED_HOSTS = ["*"]INSTALLED_APPS = [  'django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'guestbook',  #剛剛創(chuàng)建的APP,加入到此項(xiàng)目中]#數(shù)據(jù)庫(kù)默認(rèn)用sqlite3,后期可以換成MySQL或者SQL Server等TIME_ZONE = 'PRC' #時(shí)區(qū)設(shè)置為中國(guó)

創(chuàng)建數(shù)據(jù)庫(kù)字段

#encoding: utf-8from django.db import modelsclass Message(models.Model):  username=models.CharField(max_length=256)  content=models.TextField(max_length=256)  publish=models.DateTimeField()  #為了顯示  def __str__(self):    tpl = '<Message:[username={username},    return tpl.format(username=self.username, style="margin: 0px; padding: 0px; outline: none; line-height: 25.2px; font-size: 14px; width: 660px; overflow: hidden; clear: both; font-family: tahoma, arial, "Microsoft YaHei";">	
# 1. 創(chuàng)建更改的文件root@python:/online/message# python3 manage.py makemigrationsMigrations for 'guestbook': guestbook/migrations/0001_initial.py  - Create model Message# 2. 將生成的py文件應(yīng)用到數(shù)據(jù)庫(kù)root@python:/online/message# python3 manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, guestbook, sessionsRunning 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

設(shè)置項(xiàng)目message/urls.py

from django.conf.urls import url,include #添加了includefrom django.contrib import adminurlpatterns = [  url(r'^admin/', admin.site.urls),  url(r'^guestbook/', include('guestbook.urls',namespace='guestbook')),  #表示在url地址中所有g(shù)uestbook的都交給guestbook下面的url來(lái)處理,后面的逗號(hào)不要省略]

設(shè)置APP的url

如果是初次創(chuàng)建APP,urls.py在APP中一般不存在,創(chuàng)建即可

vim guestbook/urls.py

# 內(nèi)容如下from django.conf.urls import urlfrom . import viewsurlpatterns = [  url(r'^index/',views.index,name='index'),  #不要忘了逗號(hào)]

編寫(xiě)views

編輯APP中的views.py

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

編寫(xiě)HTML文件

創(chuàng)建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>留言時(shí)間</th>          <th>留言者</th>          <th>標(biāo)題</th>          <th>內(nèi)容</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">無(wú)數(shù)據(jù)</td>          </tr>        {% endif %}      </tbody>    </table>     <a class="btn btn-xs btn-info" href="/guestbook/create/" rel="external nofollow" >去留言</a>  </body></html>

調(diào)試index頁(yè)面

python manage.py runserver 0.0.0.0:99

打開(kāi)瀏覽器訪問(wèn)http://開(kāi)發(fā)機(jī)器ip地址:99/guestbook/index/

Django開(kāi)發(fā),留言板

留言展示頁(yè)面成功

創(chuàng)建留言頁(yè)面

<!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>標(biāo) 題:</label> <input type="text" name="title" placeholder="標(biāo)題" /><br /><br />        <label>內(nèi) 容:</label> <textarea name="content" placeholder="內(nèi)容"> </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'),  #不要忘了逗號(hào)  url(r'^create/$', views.create, name='create'),  url(r'^save/$', views.save, name='save'), ]

編輯views.py

#先導(dǎo)入時(shí)間模塊import datetime#添加create、savedef create(request):  return render(request, 'guestbook/create.html')def save(request):  username = request.POST.get("username")  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,再次運(yùn)行,enjoy it!

Django開(kāi)發(fā),留言板

希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 海宁市| 榆林市| 南通市| 清苑县| 巴青县| 江津市| 盐亭县| 绥阳县| 永修县| 温泉县| 德州市| 温宿县| 绥化市| 沙湾县| 龙陵县| 天津市| 南澳县| 南岸区| 苍溪县| 阜南县| 太仓市| 秦安县| 石阡县| 涟水县| 佛山市| 荃湾区| 怀宁县| 南开区| 灯塔市| 凤庆县| 大石桥市| 印江| 营山县| 鄯善县| 冀州市| 舟曲县| 镇安县| 旺苍县| 杨浦区| 黔江区| 玉田县|