Django-admin

  • create a project using this command: django-admin startproject project.
  • change to that directory cd project.
  • at this point you should be in this directory. venvi/project/
  • now open this current directory in visual studio code with command code . if this won't work open the above folder from visual studio code.

create a templates folder

  • create a templates folder in template_project folder. In project folder, not in project app which is generated by-default by django-admin.
  • the templates folder should be created where it's pointed.
. project
    ├── db.sqlite3
    ├── manage.py
    ├── project
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   ├── views.py
    │   └── wsgi.py
    └── templates <------------------------ This is where it should be created.
        
  • Now that we created a template folder we should edit settings.py to make this folder accessible to other files throughout the project.
  • open setting.py, go to templates list and add the templates directory to DIRS. 'DIRS': [BASE_DIR,'templates'].
  • After editing it should look like this.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [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',
            ],
        },
    },
]
        
  • Now whenever we mention html files in views it will check for them in this folder.

Writing main code

  • create a list.html file in the templates folder. and add these contents.
<html>
<head>
    <title>Fruit and Student List</title>
</head>
<body>
    <h1>List of Fruits</h1>
    <ul>
        <li>Apple</li>
        <li>Orange</li>
        <li>Banana</li>
        <li>Mango</li>
        <li>Strawberry</li>
    </ul>

    <h1>List of Selected Students</h1>
    <ol>
        <li>John</li>
        <li>Alice</li>
        <li>Michael</li>
        <li>Sarah</li>
        <li>David</li>
    </ol>
</body>
</html>
        
  • Now create a views.py file in project app folder and write a function to render this html file.
from django.shortcuts import render

def list(request):
    return render(request,"list.html") 
        
  • Now write a url in urls.py to redirect the request to the above view function.
from django.urls import path
from . import views

urlpatterns = [
    path("list/",views.list,name="list"),
]
        
  • Run local server python manage.py runserver and redirect url to http://127.0.0.1:8000/list/ or localhost:8000/list/

Watch a quick video summary on how to run this program

Watch it at 2x speed