Django
Very Basic Usage of Django

Initial Setup

Apps

You can create apps by running

python manage.py startapp <appname>

urls.py in an app

This file is by default created in a project, but not in the app. It is used to map urls to different apps and functions.

You can create a custom url for every app. To link an app’s url to the main project’s url, first create a urls.py in the app folder

In this file, add the following line (the first is also present in the default urls.py). The second line imports the views.py module, required to render pages.

from django.urls import path
from . import views
urlpatterns = [
    path('',views.home,name="home") #Pointing to the views module, invoke the home function.
    ]

views.py

Here, import the HttpResponse package to allow webpage renderable responses.

from django.shortcuts import render
from django.http import HttpResponse
def home(request):
    return HttpResponse("Hello World")

Main urls.py in a project

To map the urls.py from apps into the main project, thereby granting access to the app via urls in the browser, the following addition needs to be made to the main urls.py file.

Rendering Templates

First create a folder that holds your webpage html and css, say in a folder called templates in the root of your projects directory.

settings.py

The TEMPLATES tag is what renders any webpage. Add the link to the created webpage by adding the line to the TEMPLATES variable 'DIRS': [os.path.join(BASE_DIR,'templates')],.

import os
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',
            ],
        },
    },
]

app’s view.py

Modify the hello world written here to now render a page.

def home(request):    return render(request, 'index.html')

Getting inputs from the websites you create

Create a form as shown below. The function_call is the routine to be written in the urls.py of the app that will service this request.

<form action="function_call">    <input name="variable"></form>

And service the request with something like

def url_check(request):    url=request.GET["url"]    computation= url+str(1)    return render(request,"result.html",{"result":computation})