练习内容
创建message表单并渲染前端,通过前端将数据发送给后端,后端对message初步验证,验证通过存入数据库,失败返回错误信息。
接口传输 不能是dict,就是str
想要变成json类型:json.dumps( )
反序列就是 json.loads( )
>>> import json
>>> data = {'name': 'cong', 'age': 20}
>>> data
{'name': 'cong', 'age': 20}
>>> type(data)
<class 'dict'>
>>> str(data)
"{'name': 'cong', 'age': 20}"
>>> json.dumps(data)
'{"name": "cong", "age": 20}'
>>> res = json.dumps(data)
>>> res
'{"name": "cong", "age": 20}'
>>> json.loads(res)
{'name': 'cong', 'age': 20}
在app中新建forms:
# coding:utf-8
import jieba
from django import forms
from .consts import MessageType, SensitiveWordInit
# 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:
# 如果MessageType里有这个消息类型,说明这个message_type就是有效的,会返回定义的相应消息的字符串
message_type_obj = MessageType[message_type]
except Exception as e:
raise forms.ValidationError('无效的消息类型')
return message_type_obj
def clean_message(self):
content = self.cleaned_data.get('content')
if not content:
raise forms.ValidationError('消息不能为空')
cut_message = jieba.lcut(content)
check = list(set(cut_message) & set(SensitiveWordInit)) # 取交集,再转成列表
if check: # check里有内容
raise forms.ValidationError('该消息涉及违禁词汇,已被屏蔽')
return content
在consts中加一行:
SensitiveWordInit = ['专业', '生活', '内卷']
然后前端html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</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>
</form>
</body>
</html>
这个{{form.non_field_errors}}
是整体的error, {{item.errors.as_text}}
是每个item的error
运行下ok的
html再加上<input type="submit" value="提交">