Django 2 - Create html view

Nov 16, 2018 1 min read
Django 2 - Create html view

Motivation

We'd like to create an html template to use in our web.

Code

It's farely simple, just follow the steps:

  1. Create your new app: python manage.py startapp landingPage
  2. Register your app under settings.py in the main project folder (not in your newly created app) it looks like this:
    mysite/settings.py (where mysite is the name you gave it when you wrote: django-admin startproject mysite)
INSTALLED_APPS = [
    # the last part of the name (LandingpageConfig) will be located inside app.py in your new app that you created.
    'landingPage.apps.LandingpageConfig', 
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
  1. Register your templates directory. In your main project's folder, in settings.py, there is a line for TEMPLATES, make sure that your DIRS looks like this:
    mysite/settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  1. In your newly created app directory (landingPage/), create a file called: urls.py and a folder called templates, inside templates folder, create a name with the same naming as your app (landingPage) -> this is convension and good practices, nothing more.
landingPage/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    templates/
        landingPage/
            index.html
    models.py
    tests.py
    urls.py
    views.py
  1. On your views.py -> landingPage/views.py, write:
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render (request, 'landingPage/index.html')
  1. On your urls.py -> landingPage/urls.py, write:
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index')
]

You should now have a working html page. Check it by running your app:
python manage.py runserver

I hope it helps

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.