我使用Apache / PHP Server和Django中的表单来处理我的所有帖子/请求。如何设置它以便不设置字段它不会导致错误?
PHP表单:
<form action="http://www.mydomain.com:8003/login/" method="post">
<input type="text" name="email" id="email"><br>
<input type="text" name="password" id="password"><br>
<input type="checkbox" name="remember"><br>
<input type="submit" value="send" id="send">
</form>
Django的:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
if request.method == 'POST':
post = request.POST
email = post['email']
pass = post['password']
remember = post['remember']
if remember:
expire_v = 30
else:
expire_v = None
response = HttpResponse(email)
response.set_cookie('emailaddress', email, max_age=expire_v)
response.set_cookie('password', pass, max_age=expire_v)
return response
问题是如果没有检查记住而不是导致错误。
答案 0 :(得分:5)
此代码存在严重错误,并且不知道错误:从请求中获取参数时尝试使用默认值
email = request.POST.get('email', False)
password = request.POST.get('pass', False) # pass is a keyword in python
remember = request.POST.get('remember', False)
if email and password:
response = HttpResponse(email)
if remember:
response.set_cookie('emailaddress', email, max_age=30)
response.set_cookie('password', pass, max_age=30)
return response
else:
# do something to indicate a problem