jazzband/django-hosts

reverse and url tag should reverse urls without need of hostname in case of uniqness

Opened this issue ยท 4 comments

As said in docs we must pass host-name in both reverse function and url template tag.

I think it should be better if we could use something like {% url 'view-name' %} in a case that we don't have same view-names in different hosts. Or something like reverse(view_name) in such cases.

May I add this feature and make a merge request?

Any body hearing me?

I'm not sure that's a good idea as it seems to me as error-prone. You could easily add a url in the future that will break the uniqueness, and you wouldn't know about it.

I use a function for this, and find it very helpful for getting django-hosts to play well with other libraries -- perhaps it would make sense to add as an option. I would have it use the last named URL provided rather than raise an error on uniqueness.

I don't think uniqueness is a problem. Django specifically allows for re-using the same name and chooses the last one. If unintended collisions are a risk for your app, they're probably a risk regardless of how you use subdomains, and you should be using url namespaces.

For people who want this before it's officially implemented, you can make your own reverse function like this:

def reverse(*args, **kwargs):
    """
        Wrap django_hosts.reverse() to try all known hosts.
    """
    # if host is provided, just use that
    if 'host' in kwargs:
        return django_hosts.reverse(*args, **kwargs)

    # try each host
    hosts = get_host_patterns()
    for i, host in enumerate(reversed(hosts)):
        kwargs['host'] = host.name
        try:
            return django_hosts.reverse(*args, **kwargs)
        except NoReverseMatch:
            # raise NoReverseMatch only after testing final host
            if i == len(hosts)-1:
                raise

... and monkeypatch it in wherever needed.

(Oops, note also that this is a dupe of #19)