1.django的配置
message_test/settings.py
app配置部分
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'app.templatetags',
]
模板部分
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR + '/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
数据库部分
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'muke_lession_test',
'USER':'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
语言部分
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'asia/Shanghai'
2.消息管理器对于词汇的控制器
D:\python\message_test\app\templatetags\custom.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-31 9:03 PM'
import jieba
from django import template
from app.consts import SensitiveWord
import time
register = template.Library()
@register.filter(name='deep_check_message')
def deep_check(value):
# 只屏蔽关键词,替换为 * 号
cut_message = jieba.lcut(value)
new_message = []
for m in cut_message:
if m in SensitiveWord:
new_message.append('*')
else:
new_message.append(m)
if new_message:
return ''.join(new_message)
return value
@register.filter
def sample_check(value):
# 自定义的关键词过滤器
cut_message = jieba.lcut(value)
print(cut_message)
print(SensitiveWord)
check = list(set(cut_message) & set(SensitiveWord))
if len(check) != 0:
return '该消息涉及违禁词汇,已被屏蔽'
return value
@register.filter
def add_message_year(value, year):
return '{} {}'.format(value, year)
@register.filter
def date_convert(value):
timearray = time.localtime(value)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timearray)
return otherStyleTime
消息类型
D:\python\message_test\app\consts.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-31 8:28 PM'
from enum import Enum
class MessageType(Enum):
info = "info"
warning = "warning"
error = "error"
danger = "danger"
delete = "delete"
MessageType.info.label = '信息'
MessageType.warning.label = '警告'
MessageType.error.label = '错误'
MessageType.danger.label = '危险'
MessageType.info.color = 'green'
MessageType.warning.color = 'orange'
MessageType.error.color = 'gray'
MessageType.danger.color = 'red'
MessageType.delete.color = 'yellow'
SensitiveWord = ['天气', '坏人', '不开心']
SensiteveWordInit = ['专业', '生活']
3.表单部分
D:\python\message_test\app\forms.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2021-01-22 8:49 PM'
import jieba
from django import forms
from .consts import MessageType,SensiteveWordInit
MESSAGE_TYPE_CHOICE = (
(MessageType.info.value, MessageType.info.value),
(MessageType.warning.value, MessageType.warning.value),
(MessageType.error.value, MessageType.error.value),
(MessageType.danger.value, MessageType.danger.value)
)
MESSAGE_TYPE_CHOICE = tuple(
[(message.value, message.value) for message in MessageType]
)
class MessageForm(forms.Form):
content = forms.CharField(label="消息内容", max_length=100, required=True)
message_type = forms.CharField(
label='数据类型',
max_length=10,
widget=forms.Select(choices=MESSAGE_TYPE_CHOICE)
)
def clean_message_type(self):
message_type = self.cleaned_data.get('message_type')
if not message_type:
raise forms.ValidationError('消息类型不能为空')
try:
message_type_obj = MessageType[message_type]
except:
raise forms.ValidationError('无效的消息类型')
return message_type_obj
def clean_message(self):
content = self.cleaned_data.gt('content')
if not content:
raise forms.ValidationError('消息不能为空')
cut_message = jieba.lcut(content)
check = list(set(cut_message) & set(SensiteveWordInit))
if check:
raise forms.ValidationError('消息涉及违禁词汇,已被屏蔽')
return content
# 定义models
D:\python\message_test\app\models.py
# coding:utf-8
from django.db import models
from .consts import MessageType
class Message(models.Model):
content = models.TextField()
message_type = models.CharField(max_length=10, db_index=True)
created_time = models.IntegerField(default=0)
def __str__(self):
return 'type:{}, content:{}'.format(self.message_type, self.content)
@property
def message_typ(self):
try:
return MessageType[self.message_type]
except:
return MessageType.info
app路由
app/urls.py
# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-29 8:27 PM'
from django.urls import path
from .views import LessionThree, LessionFourPageOne, LessionFourPageTwo, DeleteMessage, UpdateMessage, LessionFive
urlpatterns = [
path('three/<str:message_type>', LessionThree.as_view(), name="three"),
path('fourPageOne/<str:message_type>', LessionFourPageOne.as_view()),
path('delete/', DeleteMessage.as_view()),
path('update/', UpdateMessage.as_view()),
path('fourPageTwo', LessionFourPageTwo.as_view(), name='fourpagetwo'),
path('five', LessionFive.as_view(), name='five')
]
总路由
from django.contrib import admin
from django.urls import path,include
from app import urls as app_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(app_urls))
]
视图
D:\python\message_test\app\views.py
# coding:utf-8
import time
from django.views.generic import View
# from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from .consts import MessageType
from .models import Message
from .forms import MessageForm
class LessionThree(View):
TEMPLATE = 'three.html'
def get(self, request, message_type):
data = {}
try:
message_type_obj = MessageType[message_type]
except Exception as e:
data['error'] = '没有这个消息类型{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
if not message:
data['error'] = '消息不能为空'
return render(request, self.TEMPLATE, data)
data['message'] = message
data['message_type'] = message_type_obj
# return HttpResponse(message_type)
return render(request, self.TEMPLATE, data)
class LessionFourPageOne(View):
TEMPLATE = 'four_page_one.html'
def get(self, request, message_type):
data = {}
try:
message_type_obj = MessageType[message_type]
except Exception as e:
data['error'] = '没有这个消息类型{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
if not message:
data['error'] = '消息不可为空'
return render(request, self.TEMPLATE, data)
Message.objects.create(
content=message,
message_type = message_type_obj.value,
created_time=time.time()
)
return redirect(reverse('fourpagetwo'))
class LessionFourPageTwo(View):
TEMPLATE = 'four_page_two.html'
def get(self, request):
data = {}
search = request.GET.get('search', '')
if search:
messages = Message.objects.filter(content__contains=search)
else:
messages = Message.objects.all()
data['messages'] = messages
return render(request, self.TEMPLATE, data)
class DeleteMessage(View):
def get(self, request):
id = int(request.GET.get("id", 'no such id'))
Message.objects.filter(id=id).delete()
return redirect(reverse('fourpagetwo'))
class UpdateMessage(View):
TEMPLATE = 'four_page_one.html'
def get(self, request):
data = {}
try:
id = int(request.GET.get("id", 'no such id'))
except Exception as e:
data['error'] = '找不到这个消息{}'.format(e)
return render(request, self.TEMPLATE, data)
message = request.GET.get('message', '')
print("message={}".format(message))
if not message:
data['error'] = '消息不可为空'
return render(request, self.TEMPLATE, data)
Message.objects.filter(id=id).update(content = message)
return redirect(reverse('fourpagetwo'))
class LessionFive(View):
TEMPLATE = "five.html"
def get(self, request):
data = {}
data['form'] = MessageForm()
return render(request, self.TEMPLATE, data)
def post(self, request):
form = MessageForm(request.POST)
if not form.is_valid():
return render(request, self.TEMPLATE, {'form':form})
content = form.cleaned_data.get("content", '')
message_type = form.cleaned_data.get("message_type", "")
Message.objects.create(
content=content,
message_type=message_type,
created_time=time.time()
)
return redirect(reverse('fourpagetwo'))
4.前端展示
templates/three.html
{% load custom %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if error %}
<h3>error {{ error }}</h3>
{% else %}
<label style="color:{{ message_type.color }}">{{ message_type.label }}</label>
<span style="color:{{ message_type.color }}">{{ message|deep_check_message|add_message_year:2020 }}</span>
{% endif %}
</body>
</html>
D:\python\message_test\templates\four_page_two.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% load custom %}
<h1>this page tow</h1>
{% for message in messages %}
<li style="color:{{ message.message_typ.color }}">
{{ message.id }} {{ message.content }} 时间:{{ message.created_time|date_convert }}
<a href="http://127.0.0.1:8000/delete?id={{ message.id }}">删除</a>
</li>
{% endfor %}
</body>
</html>
D:\python\message_test\templates\four_page_one.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ error }}
</body>
</html>
D:\python\message_test\templates\five.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>five</title>
</head>
<body>
<form action="{% url 'five' %}" method="POST">
{% csrf_token %}
{% for item in form %}
<div>
<label for="{{ item.id_for_label }}">
{{ item.label}}
</label>
{{ item }}
</div>
<p>
{{ item.errors.as_text }}
</p>
{% endfor %}
<span>{{ form.non_field_errors }}</span>
<input type="submit" value="提交" />
</form>
</body>
</html>
测试
![](https://i-blog.csdnimg.cn/blog_migrate/aa41eaa836a3c8d658ee4d4f079a9ff4.png)
![](https://i-blog.csdnimg.cn/blog_migrate/2910d384292a294b389c5dc6bdcf08ef.png)
admin管理模块的使用
app/admin.py
# coding:utf-8
from django.contrib import admin
from .models import Message
from django.utils.html import format_html
@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
list_display = ['id', 'content', 'message_type', 'created_time']
readonly_fields = ('message_type', 'created_time')
list_filter = ('message_type', )
search_fields = ['content']
ordering = ['-id']
list_per_page = 5
def save_model(self, request, obj, form, change):
if change:
obj.content = obj.content + " update"
else:
obj.content = obj.content + ' create'
super(MessageAdmin, self).save_model(self, obj, form, change)
def return_href(self, obj):
return format_html('<a href="{}">跳转', 'http://www.baidu.com')
app/models.py
# coding:utf-8
import time
from django.db import models
from .consts import MessageType
class Message(models.Model):
content = models.TextField()
message_type = models.CharField(max_length=10, db_index=True)
created_time = models.IntegerField(default=0)
def __str__(self):
return 'type:{}, content:{}'.format(self.message_type, self.content)
@property
def message_typ(self):
try:
return MessageType[self.message_type]
except:
return MessageType.info
def times(self):
_time = time.localtime(self.created_time)
return time.strftime('%Y-%m-%d% %H:%M:%S', _time)
![](https://i-blog.csdnimg.cn/blog_migrate/d2c7337a45374e7cfbaf3dad18581520.png)