```python
viewname_to_try = viewname
if request:
    try:
        namespace = request.resolver_match.namespace
    except AttributeError:
        try:
            namespace = resolve(request.path).namespace
        except Http404:
            namespace=None

    if namespace and ':' not in viewname:
        viewname_to_try = '{namespace}:{viewname}'.format(
            namespace=namespace, viewname=viewname)

try:
    url = django_reverse(viewname_to_try, args=args, kwargs=kwargs, **extra)
except NoReverseMatch:
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)