从上文的ajax
请求可以看出:我们点击添加之后会调用POST
,来将数据以json
的格式传输给/callections/
所以我们需要在我们的视图函数中增加CallectionsView类
的post请求部分函数。def post(self,request):
json_data = request.body
![新建接口集 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/9961238bb7f908caf05b049fdf03471a.jpeg)
在页面上点击【新建接口集】,在弹出的对话框中输入接口集名称,点击确定。
可以看到调试的时候返回的
request.body
的内容为一个
b'{"name":"666"}'
![调试 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/123673f804f290a9a3e51d9d64eb3145.jpeg)
我们需要将它转换成正常的字典格式:
json.loads(json_data.decode('utf8'))
![转换为字典格式 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/c1fc24c81561a241894ec8165ab28490.jpeg)
这样使用字典的get方法就能拿到前台传输给后台的数据了。
当获取到这个数据的时候,有两种可能:
已经创建过了
还没有创建过
from django.db import models
from utils.models import ModelBase
class Callections(ModelBase):
name = models.CharField(max_length=64, verbose_name="接口集名称", help_text="接口集名称")
class Meta:
ordering = ['-update_time', '-id']
db_table = "tb_tag" # 指明数据库表名
def __str__(self):
return self.name
这个表的结构非常简单,只需要ID和name就可以了,然而ID可以省略,所以就这样就完成了。
![数据库迁移 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/6f6d9713f3d2ad7c0442bde40643893b.jpeg)
自动新建了:apps/workspace/migrations/0001_initial.py
它是Django帮我们自动生成的一段代码,是帮助我们与数据库进行交流的。
![0001 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/c96289d9693cc5a0cff8bf366561d606.jpeg)
最后打开数据库可视化工具查看有没有生成新的表
![数据库可视化工具 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/8fe8121a194d35864c622a9d962e54eb.jpeg)
补全post接口:
def post(self, request):
json_data = request.body
if not json_data:
return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR])
# 将json转化为dict
dict_data = json.loads(json_data.decode('utf8'))
tag_name = dict_data.get('name')
if tag_name and tag_name.strip():
tag_tuple = models.Callections.objects.get_or_create(name=tag_name)
tag_instance, tag_created_bolean = tag_tuple
new_tag_dict = {
"id": tag_instance.id,
"name": tag_instance.name
}
return to_json_data(errmsg="接口集创建成功", data=new_tag_dict) if tag_created_bolean else \
to_json_data(errno=Code.DATAEXIST, errmsg="接口集名已存在")
else:
return to_json_data(errno=Code.PARAMERR, errmsg="接口集名为空")
为了测试,我们修改一下get接口
def get(self, request):
tags = models.Callections.objects.values('id', 'name')
return render(request, 'index/callections.html', locals())
将数据从数据库中拿出来,丢给html让他给我们渲染出来。
![显示 640?wx_fmt=png](https://i-blog.csdnimg.cn/blog_migrate/e1fc6b7a00953dc41d8159bafcaaca5a.png)
嘿嘿嘿,这样就完成了post提交和get的显示了,但是接口的数量还需要新建一个表,然后计算对应接口的数量。
欢迎关注我的公众号:zx94_11
![公众号 640?wx_fmt=jpeg](https://i-blog.csdnimg.cn/blog_migrate/93568d6c3251e6d0fdfa2586771dec66.jpeg)