Try/except database query in django -
i checking user's submitted email address against 2 lists database -- list of authorized domains , list of authorized email addresses. currently, if neither found, rainsing doesnotexist
exception. how handle if neither found?
here code have in views.py --
def register(request): if request.method == 'post': form = userform(request.post) if form.is_valid(): cd = form.cleaned_data try: email_list = emaillist.objects.get(domain=(cd['email'].split('@')[1])) except: email_list = emaillist.objects.get(email=cd['email']) # need except if neither works validator. network= network.objects.get(network=email_list.network) user.objects.create(name=cd['name'], email=cd['email'], network=network) return httpresponseredirect ('/user/view/') else: form = userform() return render_to_response('register.html',{'form':form}, context_instance = requestcontext(request))
you can nest try
/except
:
try: email_list = emaillist.objects.get(domain=(cd['email'].split('@')[1])) except: try: email_list = emaillist.objects.get(email=cd['email']) except: ...do else
if using these try/except simple test, it's worthwhile wrap try/except:
def get_or_none(model, **kwargs): try: return model.objects.get(**kwargs) except model.doesnotexist: return none
which gives more readable code:
if get_or_none(emaillist, domain='domain.com'): ...do elif get_or_none(emaillist, domain='domain.com'): ...do else: ...do
as ignacio mentioned in answer should explicit , catch exceptions intend.
Comments
Post a Comment