首页 > 数据库 >从前端获取数据发送到后端 存入数据库

从前端获取数据发送到后端 存入数据库

时间:2022-08-26 21:14:11浏览次数:66  
标签:obj 发送到 request publish 存入 获取数据 book authors POST

前端

{% extends 'home.html' %}

{% block contant %}

<h1 class="center" >添加图书</h1>
{# # method 一定要加上 post 并先在setting里注掉中间件#}
<form action=" " method="post">
<p>图书名称:
<input type="text" name="title" class="form-control">
</p>
<p>价格:
<input type="text" name="price" class="form-control">
</p>
<p>出版时间:
<input type="date" name="publish_date" class="form-control">
</p>
<p>出版社:
<select name="publish" id="" class="form-control">
{% for publish_obj in pubilsh_Queryset %}
<option value="{{ publish_obj.pk }}">{{ publish_obj.name }}</option>
{% endfor %}


</select>
</p>
<p>作者:
<select name="authors" id="" multiple class="form-control">
{# # multiple 是多选#}
{% for author_obj in authors_Queryset %}

<option value="{{ author_obj.pk }}">
{{ author_obj.name }}
</option>
{% endfor %}


</select>
{# # multiple 是多选#}
</p>

<input type="submit" class="btn btn-success btn-block" value="新增">



后端

def book_add(request):
# 获取前端提交过的所有数据
if request.method =='POST':
title =request.POST.get('title')
price =request.POST.get('price')
publish_date =request.POST.get('publish_date')
publish_id =request.POST.get('publish')
authors_list =request.POST.getlist('authors')
# 操作数据库,存储数据
# 书籍表
book_obj = models.Book.objects.create(title=title, price =price,publish_date=publish_date,publish_id=publish_id)
# 书与作者的关系表
book_obj.authors.add(*authors_list) #将列表打散
# 跳转到书籍的层示页面
# redirect 括号内可以直接写URL 其实也可以直接写别名,
# 但是如果你的别名有其他参数的话就要用reverse
return redirect('book_list')



pubilsh_Queryset = models.Publish.objects.all()
authors_Queryset = models.Author.objects.all()


return render(request,'book_add.html',locals())




</form>

{% endblock %}



标签:obj,发送到,request,publish,存入,获取数据,book,authors,POST
From: https://www.cnblogs.com/shclbear/p/16629272.html

相关文章