2012-11-09 88 views
3
不存在分配无值

我正在寻找一种更好的方式来代码:Django的:如果在的QueryDict

我的代码是,

@login_required 
def updateEmInfo(request):   
    userProfile = request.user.get_profile() 
    if request.POST.__contains__('userType'): 
     userType = request.POST['userType'] 
    else: 
     userType = None 

    if request.method == 'POST': 
     ~~~~~~~~ 

如果我代码userType = request.POST['userType'],然后我得到如果有错误userType不等于。

我不认为使用__contains__方法是个好主意,有没有更好的方法来编写这段代码?

东西容易像下面

userType = request.POST['userType'] ? request.POST['userType'] : None 
+0

只要一注:而不是使用'__contains__'你应该使用'in'('如果 '用户类型'在request.POST'中)。但在这种情况下,杰西的答案是准确的。 – mata

回答

3

可以使用get

request.POST.get('userType')

GET(键[默认])返回值的关键,如果关键是在 字典,否则默认。如果未给出默认值,则默认为 无,因此此方法不会产生KeyError

2

您可以使用:

userType = request.POST.get('userType', None) 

这将是大致等同于:

try: 
    userType = request.POST['userType'] 
except KeyError: 
    userType = None 
+0

谢谢!!!我不知道'get'有默认值 –