1.创建项目 cmd  django-admin startpoject cloudms 

2.创建APP cmd django-admin startapp msgapp

3.修改settings,TEMPLATES中

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR,'msgapp/templates')],
 }

4.编写HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>云端留言板(1)首页</title>
</head>
<body>
    <h1>提交留言功能区</h1>
    <form action="/msggate/" method="post">
        {% csrf_token %}
        发送方 <input type="text" name="userA" /> <br>
        接收方 <input type="text" name="userB" /> <br>
        消息文 <input type="text" name="msg" /> <br>
        <input type="submit" value="留言提交" />
    </form>

    <h1>获取留言功能区</h1>
    <form action="/msggate/" method="get">
        接收方<input type="text" name="userC" /> <br>
        <input type="submit" value="留言获取">
    </form>
    <table border="1">
        <thead>
            <th>留言时间</th>
            <th>留言来源</th>
            <th>留言信息</th>
            <th>我的留言</th>
        </thead>
        <br>
        <tbody>
            {% for line in data %}
            <tr>
                <td>{{ line.time }}</td>
                <td align="center">{{ line.userA }}</td>
                <td>{{ line.msg }}</td>
                <td>{{ line.userB }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

5.编写views文件

from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from datetime import datetime


def msgproc(requset):
    datalist = []
    if requset.method == 'POST':
        userA = requset.POST.get('userA',None)
        userB = requset.POST.get('userB',None)
        msg = requset.POST.get('msg',None)
        time = datetime.now()
        with open('msgdata.txt','a+') as f:
            f.write('{}--{}--{}--{}--\n'.format(userB,userA,\
                                                msg,time.strftime('%Y-%m-%d %H:%M:%S')))
    if requset.method == 'GET':
        userC = requset.GET.get('userC',None)
        if userC != None:
            with open('msgdata.txt','r') as f:
                cnt = 0
                for line in f:
                    linedata =line.split('--')
                    if linedata[0] == userC:
                        cnt = cnt + 1
                        d = {'userA':linedata[1],'msg':linedata[2],\
                             'time':linedata[3],'userB':linedata[0]}
                        datalist.append(d)
                    if cnt >= 10:
                        break
    return render(requset,'MsgSingleWeb.html',{'data':datalist})

6.配置本地路由:新增urls

from django.urls import path
from . import views

urlpatterns = [
    path('', views.msgproc),
]

7.配置全局路由:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('msggate/',include('msgapp.urls'))
]

8.启动项目:cmd python manage.py runserver 0:8080

版权声明:本文为ssxsy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/ssxsy/p/9096550.html