Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/except database query in django

I am checking a user's submitted email address against two lists from the database -- a list of authorized domains and a list of authorized email addresses. Currently, if neither are found, it is rainsing a DoesNotExist exception. How would I handle this if neither are found?

Here is the code I currently 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'])
            #  I also need another except if neither works for the 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))
like image 233
David542 Avatar asked Mar 03 '26 03:03

David542


1 Answers

Nested try/except blocks. And don't use a bare except; catch only the exceptions you can handle.

like image 130
Ignacio Vazquez-Abrams Avatar answered Mar 04 '26 21:03

Ignacio Vazquez-Abrams