You can set up an empty project with the command
django-admin startproject projectname
projectname within which there will be some .py files in.You can test out the created project and a simple tutorial/documentation page by running a server with the created files. cdinto the projectname folder and run
python manage.py runserver
localhost:8000You can create apps by running
python manage.py startapp <appname>
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.
]
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")
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.
Import the includes package from django.urls (from django.urls import include)
Use the includes function above to add the path to the app’s url in the main url.py (path('',include('firstapp.urls')))
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('',include('firstapp.urls'))
path('admin/', admin.site.urls),
]
First create a folder that holds your webpage html and css, say in a folder called templates in the root of your projects directory.
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',
],
},
},
]
Modify the hello world written here to now render a page.
def home(request): return render(request, 'index.html')
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})