[Solved]-Is it possible to serve a static html page at the root of a django project?

12👍

Of course you can. In cases where I just need to render a template, I use a TemplateView. Example:

url(r'^$', TemplateView.as_view(template_name='your_template.html'))

I usually order my URL patterns from most specific to least specific to avoid unexpected matches:

from django.views.generic import TemplateView

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^MyApp/', include('MyApp.urls')),
    url(r'^$', TemplateView.as_view(template_name='your_template.html')),
]

As far as where Django looks for templates, it’s up to your configuration to tell Django where to look: https://docs.djangoproject.com/en/1.8/topics/templates/#configuration

3👍

On PythonAnywhere, you can use the static files facility of your web app to serve the static file before it gets to Django:

Put a file called index.html in a directory and then point a static file entry to that directory. If the static file URL is / and the directory is the one with the html file in it, the file will be served at /.

Be aware that you don’t want the directory to be above any of your code or you’ll expose your code as static files i.e you don’t want to use the directory /somewhere/blah if your code is in /somewhere/blah/code, you’ll want to put it in /somewhere/no_code_here

👤Glenn

0👍

I have been tinkering with Django version 3.2, and I was able to serve a static HTML page at the root of the project after creating a Django app as in their official tutorial like the following in the root urls.py file:

from django.views.generic import TemplateView

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='home/base.html')),
]

This is given that home/base.html is placed where the default template folder is. If I simply re-use the polls templates directory I can create a folder like polls/templates/home/ to store base.html, for example.

Leave a comment