在Django中,处理表单的规范方式是:
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
use the form data
我想执行相同的代码,无论是没有POST还是表单无效 - 这是几行代码,所以我想知道是否有更好的方法来做这个比有两个重复的else块(一个对于内部if和一个用于外部)?
答案 0 :(得分:6)
使用单独的功能:
if request.method != 'POST':
return do_something_function_for_invalid(request)
form = SomeForm(request.POST)
if not form.is_valid():
return do_something_function_for_invalid(request)
# do something
然后将do_something_function_for_invalid()
定义为:
def do_something_function_for_invalid(request):
# do something
return response
或者,使用异常处理:
try:
if request.method != 'POST':
raise ValueError('invalid form')
form = SomeForm(request.POST)
if not form.is_valid():
raise ValueError('not a POST request')
# do something
except ValueError as ve:
# handle ve exception, ve.args[0] is the error message
答案 1 :(得分:5)
一种非常简洁的方法,不需要单独的功能,也不重复条件:
form = SomeForm(request.POST) if request.method == 'POST' else None
if form and form.is_valid():
# do your valid-submission stuff
else:
# do your invalid-submission stuff
答案 2 :(得分:0)
就像
一样简单if (request.method != 'POST') or (not SomeForm(request.POST).is_valid()):
do something