Search code examples
djangodjango-urlsdjango-subdomains

Django writing view with sudomain


With my (Django v 1.17) project I am using django-subdomains. I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html. My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404). Hete is my code:

settings.py

INSTALLED_APPS = [
   'subdomain'
]
SUBDOMAIN_URLCONFS = {

    'subdomain': 'subdomain.urls',

}

subdomain/urls.py

 from django.conf.urls import url, include

from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$example', views.example, name='example'),
]

subdomain/views.py

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse

def index(request):
    template = loader.get_template('subdomain/index.html')
    return HttpResponse(template.render())


def example(request):
    template = loader.get_template('subdomain/example.html')
    return HttpResponse(template.render())

Error:

    Page not found (404)
    Request Method: GET
    Request URL:    https://subdomain.domain.com/example
    Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
   1. ^$ [name='index']
   2. ^$example [name='example']

    The current path, econ, didn't match any of these. 

Please advise how to fix this issue and write view for sub-domain.


Solution

  • This is unrelated to django-subdomains. The dollar should be at the end of the regex.

    url(r'^example$', views.example, name='example'),
    

    The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.