POST和GET是web开发中常用的表单交互方法,是构建web前后端交互系统的顶梁柱,现将Django中的简单用法示例记录下来,以供后续查询和其他同学参考
1.URL传参
1
2
3
4
5
6
|
#前端html的链接中用模版标签把参数"x"传递给achievement这个应用的yearcontent方法
< td >< a href={% url 'achievement:yearcontent' x %} >{{ x }}</ a ></ td >
#urls.py中用正则匹配接收参数,(?P< year >[0-9]+)用括号括起来接收前端传过来的x=2017,好传给视图函数views.py使用,?P用于设置匹配部分的名字,views.py里面要用这个名字来接收参数的,[0-9]+表示正则匹配所有整数
url(r'^yearcontent/(?P< year >[0-9]+)/$', views.yearcontent, name='yearcontent'),
#views.py里面接收传过来的year=2017,后续方法体中再用传过来的参数搞事情,这就是用URL传参也就是GET方法的一种使用
def yearcontent(request,year):
|
2.FORM表单 用POST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#前端html中设置好name,因为后续要通过name获得数据
< form class = "form-horizontal" role = "form" action = "{% url 'achievement:set_new_purpose' %}" method = "post" >
{% csrf_token %}
< div class = "form-group" >
< label class = "col-lg-2 control-label" >目标</ label >
< div class = "col-lg-10" >
< input type = "text" class = "form-control" id = "cc" placeholder = "" name = "achievement_title" >
</ div >
</ div >
< div class = "form-group" >
< label class = "col-lg-2 control-label" >备注</ label >
< div class = "col-lg-10" >
< textarea id = "" class = "form-control" cols = "30" rows = "10" name = "achievement_text" ></ textarea >
</ div >
</ div >
< div class = "form-group" >
< div class = "col-lg-offset-10" >
< button type = "submit" class = "btn btn-send" type = "submit" >确定</ button >
</ div >
</ div >
</ form >
#urls中
url(r'^set_year_summary$', views.set_year_summary, name='set_year_summary'),
#视图函数views.py中, request.POST[name]来接收form表单的数据,然后就可以搞事情了
def set_year_summary(request):
achievement_date = request.POST['year']
achievement_summary = request.POST['achievement_text']
twz = AchievementYear.objects.get(achievement_date=achievement_date)
print twz
twz.achievement_summary = achievement_summary
twz.save()
return redirect('achievement:index')
|
以上这篇基于Django URL传参 FORM表单传数据 get post的用法实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u013205877/article/details/77778061