GithubHelp home page GithubHelp logo

jazzband / django-hosts Goto Github PK

View Code? Open in Web Editor NEW
962.0 24.0 104.0 425 KB

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.

Home Page: http://django-hosts.rtfd.org

License: Other

Makefile 0.42% Python 99.58%

django-hosts's Introduction

django-hosts

https://readthedocs.org/projects/django-hosts/badge/?version=latest&style=flat

This Django app routes requests for specific hosts to different URL schemes defined in modules called "hostconfs".

For example, if you own example.com but want to serve specific content at api.example.com and beta.example.com, add the following to a hosts.py file:

from django_hosts import patterns, host

host_patterns = patterns('path.to',
    host(r'api', 'api.urls', name='api'),
    host(r'beta', 'beta.urls', name='beta'),
)

This causes requests to {api,beta}.example.com to be routed to their corresponding URLconf. You can use your urls.py as a template for these hostconfs.

Patterns are evaluated in order. If no pattern matches, the request is processed in the usual way, ie. using the standard ROOT_URLCONF.

The patterns on the left-hand side are regular expressions. For example, the following ROOT_HOSTCONF setting will route foo.example.com and bar.example.com to the same URLconf.

from django_hosts import patterns, host

host_patterns = patterns('',
    host(r'(foo|bar)', 'path.to.urls', name='foo-or-bar'),
)

Installation

First, install the app with your favorite package manager, e.g.:

pip install django-hosts

Alternatively, use the repository on Github.

You can find the full docs here: django-hosts.rtfd.org

Then configure your Django site to use the app:

  1. Add 'django_hosts' to your INSTALLED_APPS setting.

  2. Add 'django_hosts.middleware.HostsRequestMiddleware' to the beginning of your MIDDLEWARE setting.

  3. Add 'django_hosts.middleware.HostsResponseMiddleware' to the end of your MIDDLEWARE setting.

  4. Create a new module containing your default host patterns, e.g. in the hosts.py file next to your urls.py.

  5. Set the ROOT_HOSTCONF setting to the dotted Python import path of the module containing your host patterns, e.g.:

    ROOT_HOSTCONF = 'mysite.hosts'
  6. Set the DEFAULT_HOST setting to the name of the host pattern you want to refer to as the default pattern. It'll be used if no other pattern matches or you don't give a name to the host_url template tag.

django-hosts's People

Contributors

adamchainz avatar andriyor avatar apollo13 avatar avilaton avatar bak1an avatar bashu avatar bretth avatar browniebroke avatar charettes avatar ddabble avatar hramezani avatar jazzband-bot avatar jefftriplett avatar jezdez avatar joshuadavidthomas avatar justinvelluppillai avatar lamby avatar leminaw avatar markush avatar max-muoto avatar mikevl avatar mvantellingen avatar philipn avatar smithdc1 avatar stianjensen avatar timgraham avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-hosts's Issues

Feature Request/Idea Autmatically try all host confs.

The ability to override the url tag is a great help for 3rd party apps, but I think instead of falling back to the default host, all host confs should be tried (maybe behind a setting): Assuming a site hosts a blog, forum and a wiki it would be great if the url tag would just try to reverse on all available host confs. This obviously only works for the cases where the subdomain is static, but I think this is a relatively common scenario. Is this something you'd support, if yes I'd see what I can do about that.

Implications would be that the urlnames have to be unique, or otherwise just let the first match win, but I think that urlnames are and should be unique anyways. Performance wise there should be no downside either, as having a single domain with all urls would require iteration over all anyways…

django-hosts requires *.dist-info metadata

django-hosts raise an error if no *dist-info metadata is present

pkg_resources.DistributionNotFound: The 'django-hosts' distribution was not found and is required by the application

Possible actions:

  • set __version__ manually
 __version__ = '1.2.3'
  • wraps call into a try/except block
try:
    import pkg_resources
    VERSION = pkg_resources.get_distribution('django-hosts').version
except Exception:
    VERSION = 'unknown'
  • others?

django_hosts.resolvers.reverse NoReverseMatch with wildcard regex

Not sure if I'm missing something, but I'm having trouble using reverse on wildcard subdomains.

hosts.py

from django.conf import settings
from django_hosts import patterns, host

host_patterns = patterns('',
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'(\w+)', app.custom_urls', name='wildcard'),
)

app.custom_urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url

from app import views


urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^articles/', include('app.articles.urls', namespace='articles')),
    url(r'^events/', include('app.events.urls', namespace='events')),
    url(r'^partners/', include('app.partners.urls', namespace='partners')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Now if I try something like:

from django_hosts.resolvers import reverse

reverse('home', host='wildcard')

I'm getting the error:

NoReverseMatch                            Traceback (most recent call last)
<ipython-input-2-e86d09f05052> in <module>()
----> 1 reverse('home', host='wildcard')

/Users/vitorfs/Development/venv/lib/python2.7/site-packages/django_hosts/resolvers.pyc in reverse(viewname, args, kwargs, prefix, current_app, host, host_args, host_kwargs, scheme, port)
    167     hostname = reverse_host(host,
    168                             args=host_args,
--> 169                             kwargs=host_kwargs)
    170     path = reverse_path(viewname,
    171                         urlconf=host.urlconf,

/Users/vitorfs/Development/venv/lib/python2.7/site-packages/django_hosts/resolvers.pyc in reverse_host(host, args, kwargs)
    119     raise NoReverseMatch("Reverse host for '%s' with arguments '%s' "
    120                          "and keyword arguments '%s' not found." %
--> 121                          (host.name, args, kwargs))
    122 
    123 #: The lazy version of the :func:`~django_hosts.resolvers.reverse_host`

NoReverseMatch: Reverse host for 'wildcard' with arguments '()' and keyword arguments '{}' not found.

Now if I change my hosts.py

hosts.py (removed regex)

from django.conf import settings
from django_hosts import patterns, host

host_patterns = patterns('',
    host(r'www', settings.ROOT_URLCONF, name='www'),
    host(r'test', app.custom_urls', name='wildcard'),
)

I can run:

In [1]: from django_hosts.resolvers import reverse

In [2]: reverse('home', host='wildcard')
Out[2]: '//test.testserver.local/'

Which is correct.

Tests that include MockViews fail.

I have some testcases in which i make use of a MockView to test my custom authentication classes.

class MockView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})

    def post(self, request):
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})

    def put(self, request):
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})


urlpatterns = [
    url(
        r'^organisationauth/$',
        MockView.as_view(authentication_classes=[SymmetricOrganisationJWTAuth])
    ),
    url(
        r'^appauth/$',
        MockView.as_view(authentication_classes=[SymmetricApplicationJWTAuth])
    ),
]

To use this mocks i had to use the override_settings decorator:

@override_settings(ROOT_URLCONF='mysite.tests.test_auth')
class OrganiationSymmetricKeyTest(APITestCase):
...

After installing and configuring django-hosts that override doesn't seem to work anymore:
AssertionError: 404 != 403

All other tests pass. Any idea?

can i use parameter

Hello,i use django-host in this case:

{% for action in actions_list %}
<li>
    <a href="{% url  action.url_alias %}">{{ action.name_short }}</a>
</li>
{% endfor %}

and it error:

Reverse for ''user-edit' 1 host 'account'' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

how can i solve this problem? any one help?

Adjust travis configuration to make the deployment to PyPI happen only once per build

At the moment every build in matrix (for tagged commits of course) attempts to do the deployment.

Example:
https://travis-ci.org/jazzband/django-hosts/builds/96972410

As we can see #101.1 has deployed the release to PyPI, while other six builds in the matrix failed to do so with:

Uploading distributions to https://pypi.python.org/pypi
Uploading django_hosts-1.3-py2.py3-none-any.whl
HTTPError: 400 Client Error: A file named "django_hosts-1.3-py2.py3-none-any.whl" already exists for  django-hosts-1.3. To fix problems with that file you should create a new release. for url: https://pypi.python.org/pypi

This seems to be easy to fix using conditional releases. We just need to select one tox env that will be responsible for deploying.

More accurate solution would be to deploy only when all builds are finished. However, I have not found the solution for this yet.

The similar procedure can be done for other repositories under jazzband.

import reverse shadow issue

from django_hosts import reverse
imports deprecated module django_hosts.reverse instead of most important and actually desired django_hosts.resolvers.reverse function, basically module effectively shadows the import currently in django_hosts.__init__.py, namely from django_hosts.resolvers import reverse.
Considering the fact that django_hosts.reverse module will be removed in the next version anyways, nothing needs to be done. This issue is opened simply to record that from django_hosts import reverse will not work as desired until next release.

Issue with admin routing

The default admin app doesn't have a urls.py in it. So how can I use the admin site at admin.mysite.com ? What will be in the hosts.py?

site caching

I was having trouble, but finally figured out it won't work properly with site caching. I needed to disable site wide caching, i.e. middleware django.middleware.cache.FetchFromCacheMiddleware.

Any way around this or should I just switch to more granular, per-view caching?

ImproperlyConfigured: Error importing module django_hosts.middleware: "No module named lru_cache"

I get this exception with 1.2 version. I'm using it with Django 1.6.10.

[14/May/2015 18:52:35] "GET / HTTP/1.1" 500 59
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
    self.load_middleware()
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 45, in load_middleware
    mw_class = import_by_path(middleware_path)
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_by_path
    sys.exc_info()[2])
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 21, in import_by_path
    module = import_module(module_path)
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django_hosts/middleware.py", line 5, in <module>
    from .resolvers import get_host_patterns, get_host
  File "/home/me/dev/venvs/proj/local/lib/python2.7/site-packages/django_hosts/resolvers.py", line 15, in <module>
    from django.utils.lru_cache import lru_cache
ImproperlyConfigured: Error importing module django_hosts.middleware: "No module named lru_cache"

Retry the 2.0 release

I tried to release 2.0 today but uploading to PyPI failed because the "Framework :: Django :: 1.10" classifier doesn't exist yet. After that's resolved, what do you think is the best way to retry the release? I thought of deleting and recreating the tag -- not sure if that might have some undesired side effect.

Django 1.9 Warnings

Most of my console warnings are triggered by Django-hosts:

/home/nekmo/.virtualenvs/exiscontacts/src/django-hosts/django_hosts/resolvers.py:14: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
  from django.utils.importlib import import_module

/home/nekmo/.virtualenvs/exiscontacts/src/django-hosts/django_hosts/resolvers.py:31: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Dj
ango 1.9. Use django.utils.lru_cache instead.
  get_hostconf = memoize(get_hostconf, _hostconf_cache, 0)

/home/nekmo/.virtualenvs/exiscontacts/src/django-hosts/django_hosts/resolvers.py:38: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Dj
ango 1.9. Use django.utils.lru_cache instead.
  get_hostconf_module = memoize(get_hostconf_module, _hostconf_module_cache, 1)

/home/nekmo/.virtualenvs/exiscontacts/src/django-hosts/django_hosts/resolvers.py:51: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Dj
ango 1.9. Use django.utils.lru_cache instead.
  get_host = memoize(get_host, _host_cache, 1)

/home/nekmo/.virtualenvs/exiscontacts/src/django-hosts/django_hosts/resolvers.py:62: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Dj
ango 1.9. Use django.utils.lru_cache instead.
  get_host_patterns = memoize(get_host_patterns, _host_patterns_cache, 0)

Django 1.8 deprecation warning for memoize

Updating to django 1.8 shows the following deprecation warnings:

/python3.4/site-packages/django_hosts/resolvers.py:31: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Django 1.9. Use django.utils.lru_cache instead.
  get_hostconf = memoize(get_hostconf, _hostconf_cache, 0)

/python3.4/site-packages/django_hosts/resolvers.py:38: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Django 1.9. Use django.utils.lru_cache instead.
  get_hostconf_module = memoize(get_hostconf_module, _hostconf_module_cache, 1)

/python3.4/site-packages/django_hosts/resolvers.py:51: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Django 1.9. Use django.utils.lru_cache instead.
  get_host = memoize(get_host, _host_cache, 1)

/python3.4/site-packages/django_hosts/resolvers.py:62: RemovedInDjango19Warning: memoize wrapper is deprecated and will be removed in Django 1.9. Use django.utils.lru_cache instead.
  get_host_patterns = memoize(get_host_patterns, _host_patterns_cache, 0)

domain and port

Django does some magic to include the domain and port (and the schema) in reverse urls without the need of additions in the settings module. Wouldn't it be nice if django-hosts provided similar functionality? In my opinion, reverse() and host_url template tag should work similarly to django counterparts.

Cut a release?

Pretty please? ❤️

(0.4.1 still carries the lingering Django requirement.)

Document how to build the docs

make html gives DistributionNotFound: django-hosts (even after pip install -e django-hosts)

PYTHONPATH=.. make html gives ImportError: No module named django.conf

Are things somewhat broken in the current state or a I missing something?

No reverse match when url has arguments

This is my url config with the host 'app'

url(r'^my-services/(?P<pk>[0-9]+)/update/$', views.service_update, name="service_update")

And this is my template tag. I've tried hard coding the value for pk with the valid value but it still would not work.
{% host_url 'service_update' host 'app' pk=service.id%}

host_url tag does not preserve server port

Development server is running at http://127.0.0.1:8000/

Urls generated by host_url tag do not contain ":8000". Fixing the port in settings.PARENT_HOST can help, but not for tests.

I'm running tests with django.test.LiveServerTestCase (Django 1.4). Live server port can not be predicted, it would be nice to determine the actual port at runtime.

Conflict with django-debug-toolbar

django-debug-toolbar does not work if its middleware placed before django-hosts middleware. On the other side - if django-debug-toolbar middleware is placed after django-hosts middleware - last one does not work.

Support for django1.9?

Trying to upgrade to django 1.9 today and it seems like django-hosts is the culprit of this :

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

When I remove django-hosts from INSTALLED_APPS this stops showing up

admin routing

hey great addon for django :)

but i have a problem:

i have 2 subdomains and all subdomains should be route to one admin interface

host(r'(app1|app2)/admin', 'urls', name="app1-or-app2"),                                                                                                                                                                                      
host(r'(app1)', 'app1.urls', name="app1"),                                                                                                                                                                                      
host(r'(app2)', 'app2.urls', name="app2"),                                                                                                                                                                                      

ROOT_URLCONF = 'urls'                                                                                                                                                                                                                      
ROOT_HOSTCONF = 'hosts'                                                                                                                                                                                                                    
DEFAULT_HOST = 'app1'

DO you have an idea?
thanks :)

url_name and host_name in host_url template tag as template variable

Is it possible to pass url_name and host_name and the parameters as template variable?

i use database to store the variable, and in temple like this:
{% for action in actions_list %}

  • {{ action.name_short }}
  • {% endfor %}

    the action.url_alias is like this 'user-edit' 1 host 'account'

    but it error:

    Reverse for ''user-edit' 1 host 'account'' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

    how can i solve this problem? any one help?

    any help? thanks a lot

    Django-Hosts Routing issue in Production

    Django-hosts is working perfectly fine on my development server. But it's not working fine on the production server. when I visit m.example.com it will redirect me to example.com.

    I have one project with different apps. I only want the subdomain to make use of mravmomentapp.

    E.g

    project name: mrav
    apps under: mrav/moneapp
                       mrav/mtwoapp
                       mrav/mravmomentapp
    

    My stack is nginx, wsgi, gunicorn.

    I placed the hosts.py in mrav/hosts.py

    In my hosts.py

    if socket.gethostname()=="AM-PC":
        host_patterns = patterns('',
                host(r'examplelocal.com:8000', mrav_base_settings.ROOT_URLCONF, name='www'),
            host(r'm.examplelocal.com:8000', 'mravmomentapp.urls', name='m'),
        )
     ###use this settings in production
    else: 
          host_patterns = patterns('',
               host(r'example.com', mrav_base_settings.ROOT_URLCONF, name='www'),
            host(r'm.example.com', 'mravmomentapp.urls', name='m'),
          )
    

    In my mravmomentapp.urls I have

         urlpatterns =[
               url(r'^$', mo_views.home_page, name='home_page'),  #homepage for subdomain  m.example.com 	
             ]
    

    in my nginx.conf

        server {
             listen 80;
             listen [::]:80;
             server_name example.com www.example.com *.example.com m.example.com;
             return 301 https://$server_name$request_uri;
       }
    
    
        server {
               listen 443 ssl http2;
               listen [::]:443 ssl http2;
                server_name example.com www.example.com;
                 index  index.html index.htm index.php;
                include snippets/ssl-example.com.conf;
                 include snippets/ssl-params.conf;
    
              location / {
                    include proxy_params;
                    proxy_pass http://mrav_app_server;
             }
    
               #othersettings
    
        }
    

    I also created an A host file in my DNS and added my IP ADDRESS to it.

    What am I missing?

    Blank or www catches url with subdomain

    If I have the following hosts.py:-

    host_patterns = patterns(
        '',
    
        host(
            r'|www',
            'config.urls.cc',
            name='main'
        ),
    
    host(
            r'manage',
            'config.urls.manage',
            name='manage'
        ),
    
        host(
            r'(?P<subdomain>\w+)',
            settings.ROOT_URLCONF,
            name='other'
        ),
    )
    

    and I go to example.com or www.example.com, I'd expect it to match the 1st host, which it does.

    But if I go to manage.example.com, I'd expect it to match the 2nd in the list - or if I go to somethingelse.example.com, I'd expect it to match the last host. However, both of these urls are matched by the 1st host (the cc one).

    Any ideas?

    Update for removal of add_to_builtins() in Django 1.9

    Django 1.9 removes django.template.base.add_to_builtins() in favor of a formalized API.

    To ease the migration, in AppConfig.ready() we could throw an error if settings.HOST_OVERRIDE_URL_TAG=True and add_to_builtins isn't importable (Django 1.9+). The error would inform the user to add 'django_hosts.templatetags.hosts_override' to the TEMPLATES['OPTIONS']['builtins'] setting. I think it's probably better than updating the TEMPLATES automatically. This approach would allow us to eventually remove settings.HOST_OVERRIDE_URL_TAG too.

    This would require removing HOST_OVERRIDE_URL_TAG=True from settings in order to silence the upgrade error then -- is it okay? I think most projects (not reuseable apps) don't try to support multiple versions of Django at once. If we need to be able to define one settings file that works with multiple versions of Django, then we'll need a different approach.

    What about a new release?

    Hi! I'm not sure if it's a right place for my question. Sorry about that. May, 6 - It was so long ago. Now, I get warnings in django 1.8. At the same time, master branch contains some commits fixing these warnings.

    Django 1.8 error: ImportError: cannot import name add_to_builtins

    The version of Pypi is not working in Django 1.8. An error occurs trying to import:

      File "/home/nekmo/.virtualenvs/xxxx/local/lib/python2.7/site-packages/django_hosts/apps.py", line 4, in <module>
        from django.template import add_to_builtins
    ImportError: cannot import name add_to_builtins
    

    Please, update Pypi repo.

    Using django-hosts on multi-language site

    Hello! I tried to use django-hosts with 'django.middleware.locale.LocaleMiddleware', https://docs.djangoproject.com/en/1.10/topics/i18n/translation/ but it seems doesn't work.

    For ex. without django-hosts URL is xxx.yy/ru/app_name, or xxx.yy/en/app_name
    but when I use django-hosts URL is zzz.xxx.yy/, if I'm trying zzz.xxx.yy/ru or zzz.xxx.yy/en
    I'm getting error, as 'django.middleware.locale.LocaleMiddleware', uses language routing with the top level urls.py, but with django-hosts routing goes directly to app's urls. I'tried to move i18n_patterns block from root urls.py to app's urls.py, but I'm getting error "django.core.exceptions.ImproperlyConfigured: Using i18n_patterns in an included URLconf is not allowed."

    Are there any possibilities to use i18n with django-hosts?

    NoReverseMatch: u'admin' is not a registered namespace

    [19/Apr/2017 16:15:12] "GET / HTTP/1.1" 302 0
    Internal Server Error: /login/
    Traceback (most recent call last):
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner
        response = get_response(request)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/core/handlers/base.py", line 217, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/core/handlers/base.py", line 215, in _get_response
        response = response.render()
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/response.py", line 109, in render
        self.content = self.rendered_content
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/response.py", line 86, in rendered_content
        content = template.render(context, self._request)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render
        return self.template.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 208, in render
        return self._render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/test/utils.py", line 94, in instrumented_test_render
        return self.nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/loader_tags.py", line 174, in render
        return compiled_parent._render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/test/utils.py", line 94, in instrumented_test_render
        return self.nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/loader_tags.py", line 174, in render
        return compiled_parent._render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/test/utils.py", line 94, in instrumented_test_render
        return self.nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/loader_tags.py", line 70, in render
        result = block.nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/defaulttags.py", line 315, in render
        return nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/loader_tags.py", line 70, in render
        result = block.nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/defaulttags.py", line 315, in render
        return nodelist.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 994, in render
        bit = node.render_annotated(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/base.py", line 961, in render_annotated
        return self.render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django_hosts/templatetags/hosts.py", line 45, in render
        path = super(HostURLNode, self).render(context)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/template/defaulttags.py", line 439, in render
        url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
      File "/home/user/.pyenv/versions/webev.net/lib/python2.7/site-packages/django/urls/base.py", line 87, in reverse
        raise NoReverseMatch("%s is not a registered namespace" % key)
    NoReverseMatch: u'admin' is not a registered namespace

    website/hosts.py:

    from __future__ import unicode_literals
    
    from django_hosts import patterns, host
    
    host_patterns = patterns('',
        host(r'www', 'website.urls', name='www'),
        host(r'admin', 'website.urls.admin', name='admin'),
    )

    website/urls/__init__.py:

    from __future__ import unicode_literals
    
    from django.conf import settings
    from django.conf.urls import url, include
    from django.views.generic import TemplateView
    
    urlpatterns = [
        url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
    ]
    if settings.DEBUG:
        import debug_toolbar
        from django.conf.urls.static import static
        urlpatterns += [url(r'^__debug__/', include(debug_toolbar.urls)),]
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

    website/urls/admin.py

    from __future__ import unicode_literals
    
    from django.contrib import admin
    from django.conf.urls import url, include
    
    urlpatterns = [
        url(r'^', admin.site.urls),
    ]

    What am I doing wrong? Any help is greatly appreciated.

    Django 1.10 compatibility

    I'm working on compatibility with 1.10. Just outlining here what changes need to be made.

    • middleware deprecated since 1.10
    • patterns deprecated since 1.8
    • string views deprecated since 1.8
    • django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured - default TEMPLATE_LOADERS deprecated since 1.8, need to add TEMPLATES
    • Private api Model._meta.get_all_field_names() removed in 1.10

    One side issue I have is that running tox, setuptools_scm doesn't install on py34 and I don't have time to go down that rabbithole.

    No scheme URI should be possible

    Right now it is not possible to have URIs without a scheme for relative links. Unfortunately normalize_scheme makes sure that there is always a // in place.

    The documentation itself gives the example of <a href="//admin/dashboard/">Admin dashboard</a>. If admin is not a hostname/domain, this would not lead anywhere. I would suggest that admin/dashboard/ would be the better URI to build here.

    I would suggest to change normalize_scheme to accept an empty string as well.

    Simple test example

    I don't follow how you're meant to write tests for endpoints running via django-hosts – I've attempted overriding settings and passing hostnames... and still the default urlconf is being triggered.

    An example of how you intend people to test these routes would be useful. Should I be doing something like setting the test client hostname to api.testserver, is that meant to work?

    resolvers.reverse not pointing to domain, am I doing something wrong?

    Django 1.8.2, django-hosts 1.2

    Config:

    host_patterns = patterns('',
        host(r'', 'project.urls', name='root'),
        host(r'www', 'project.urls', name='www'),
    ...
    

    Django shell example:

    >>> from django_hosts.resolvers import reverse
    >>> reverse("namespace:view", kwargs={'arg':8, 'pk':1}, host='www')
    '//www/arg8/pk/1/'
    >>> reverse("namespace:view", kwargs={'arg':8, 'pk':1}, host='root')
    '///arg8/pk/1/'
    

    Why isn't it //www.domain.com/arg8/pk/1/?

    CSRF_FAILURE_VIEW for each host rule?

    Hi,

    I'm having a problem which for 'csrf fail' on my api.host, the result is the 'csrf_failure_view' of my website.
    The problem is that once it has some 'url' template tags (that don't have matching on the 'api' host, it gives and Internal Server Error (500).

    Any way of specifing an 'host' independent setting for this?
    Or maybe, creating an intermediate view that handles the domain part, and based on that result, shows and specific view for each domain?

    Thanks for any help,
    Felipe

    settings.APPEND_SLASH is ignored on subdomains

    Django raises 404 on http://subdomain.mydomain.com/mypage while http://subdomain.mydomain.com/mypage/ works as expected.

    Pattern: r'^mypage/$'
    Version: 1.4
    Django: 1.8
    Middleware order:

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware',
    
        'django_hosts.middleware.HostsRequestMiddleware',
    
        'mymiddleware',
    
        'django_hosts.middleware.HostsResponseMiddleware',
    )
    

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.