Django的views.py中怎么区别用户是点击的哪个<input>后返回函数的?比如说我写了两个submit类型的<input>,但是一个用来返回主页,另一个用来继续填写下一张表单
时间: 2024-03-16 09:45:15 浏览: 13
在Django的views.py中,可以通过request对象中的一些属性来区分用户点击的是哪个<input>。常用的属性包括:
1. request.method:用于获取请求的方法,GET或POST。
2. request.POST:用于获取POST请求中提交的所有数据,返回的是一个字典。
3. request.GET:用于获取GET请求中提交的所有数据,返回的也是一个字典。
通过判断这些属性的值,可以区分用户点击的是哪个<input>。比如,可以在views.py中写两个函数,一个处理返回主页的<input>,另一个处理继续填写下一张表单的<input>,然后在模板中指定对应的URL和函数即可。
示例代码:
```python
# views.py
from django.shortcuts import render, redirect
def index(request):
# 处理返回主页的<input>
if request.method == 'POST' and 'home' in request.POST:
return redirect('home')
return render(request, 'index.html')
def next_form(request):
# 处理继续填写下一张表单的<input>
if request.method == 'POST' and 'next_form' in request.POST:
# do something
return redirect('next_form')
return render(request, 'next_form.html')
# index.html
<form method="post">
{% csrf_token %}
<input type="submit" name="home" value="返回主页">
</form>
# next_form.html
<form method="post">
{% csrf_token %}
<input type="submit" name="next_form" value="继续填写下一张表单">
</form>
```
在这个示例中,我们在index.html和next_form.html中分别定义了一个<input>,并指定了对应的name属性(home和next_form)。在views.py中,我们分别编写了两个函数来处理这两个<input>的请求,通过判断request对象中的method和POST属性来区分用户点击的是哪个<input>。如果是返回主页的<input>,则重定向到主页,如果是继续填写下一张表单的<input>,则执行相应的逻辑再重定向到下一张表单的页面。