如何在Django视图中获取POST请求值?
我正在尝试通过html和django制作一个注册表单,所以我有三个输入框,让用户填写邮箱、用户名和密码,然后通过POST请求把这些信息发送到/adduser。
<form action="/OmniCloud_App/adduser" method="post">
{% csrf_token %}
Email Address: <input type="text" name="email" /></br>
Username: <input type="text" name="username" maxlength=25 /></br>
Password: <input type="password" maxlength=30 /></br>
</br>
<input type="submit" value="Send" /> <input type="reset">
</form>
adduser会创建一个新的用户并把它保存到数据库里:
def adduser(request, email, username, password):
u = User(email=email, username=username, password=password)
u.save()
return render_to_response('adduser.html', {'email':email, 'username':username, 'password':password})
但是当我在/signup页面点击提交时,它提示我只提供了一个参数,而实际上需要三个参数。我应该如何把signup.html中的邮箱、用户名和密码传递给位于/username的函数呢?
3 个回答
0
比如说,如果你在 index.html
中提交了下面的 POST
请求值:
{# "index.html" #}
<form action="{% url 'my_app1:test' %}" method="post">
{% csrf_token %}
<input type="text" name="fruits" value="apple" /></br>
<input type="text" name="meat" value="beef" /></br>
<input type="submit" />
</form>
那么,你可以在 my_app1/views.py
中获取到这些 POST
请求值,具体方法如下。*我的回答 里有更详细的解释:
# "my_app1/views.py"
from django.shortcuts import render
def test(request):
print(request.POST['fruits']) # apple
print(request.POST.get('meat')) # beef
print(request.POST.get('fish')) # None
print(request.POST.get('fish', "Doesn't exist")) # Doesn't exist
print(request.POST.getlist('fruits')) # ['apple']
print(request.POST.getlist('fish')) # []
print(request.POST.getlist('fish', "Doesn't exist")) # Doesn't exist
print(request.POST._getlist('meat')) # ['beef']
print(request.POST._getlist('fish')) # []
print(request.POST._getlist('fish', "Doesn't exist")) # Doesn't exist
print(list(request.POST.keys())) # ['csrfmiddlewaretoken', 'fruits', 'meat']
print(list(request.POST.values())) # ['b0EQnFlWoAp4pUrmsFxas43DYYTr7k04PhhYxqK3FDTBSXWAkJnsCA3GiownZQzS', 'apple', 'beef']
print(list(request.POST.items())) # [('csrfmiddlewaretoken', 'b0EQnFlWoAp4pUrmsFxas43DYYTr7k04PhhYxqK3FDTBSXWAkJnsCA3GiownZQzS'), ('fruits', 'apple'), ('meat', 'beef')]
print(list(request.POST.lists())) # [('csrfmiddlewaretoken', ['b0EQnFlWoAp4pUrmsFxas43DYYTr7k04PhhYxqK3FDTBSXWAkJnsCA3GiownZQzS']), ('fruits', ['apple']), ('meat', ['beef'])]
print(request.POST.dict()) # {'csrfmiddlewaretoken': 'b0EQnFlWoAp4pUrmsFxas43DYYTr7k04PhhYxqK3FDTBSXWAkJnsCA3GiownZQzS', 'fruits': 'apple', 'meat': 'beef'}
print(dict(request.POST)) # {'csrfmiddlewaretoken': ['b0EQnFlWoAp4pUrmsFxas43DYYTr7k04PhhYxqK3FDTBSXWAkJnsCA3GiownZQzS'], 'fruits': ['apple'], 'meat': ['beef']}
return render(request, 'test.html')
2
它们会在 request.POST
里面,你可以像查询一个 dict
(字典)一样去查找它们。
email = request.POST.get('email')
username = request.POST.get('username')
password = request.POST.get('password')
2
如果你阅读了教程的第三部分,你会发现视图函数需要从网址中获取一些部分作为参数。如果你继续看同一个教程的第四部分,你会了解到POST参数是通过request.POST
来获取的。在文档的后面,你还会学到可以编写表单类,这些类可以处理HTML表单的生成和验证。