Django is a web framework written in the Python programming language aimed at building web applications quickly. Django is free, opened source, and maintained by Django Software Foundation.
Opinionated frameworks recommend specific ways of solving problems to streaming productivity.
A project installation comes with administrative tools to deploy a development server immediately after establishing a project.
python3 manage.py runserver
URLs are mapped to a view function, which processes a user’s web request and sends a response back.
def home(request):return HttpResponse("This is a response from the server.")
A project is a collection of configurations and individual apps for a particular website. Each app should have a clearly defined purpose.
A project is started using the startproject
command.
django-admin startproject myproject
manage.py is a file that includes commands to administer a Django app.
The settings.py file contains the project settings for a Django project.
A project installation comes with administrative tools to deploy a development server immediately after establishing a project.
python3 manage.py runserver
A Django server can be stopped by pressing ctrl + c.
The development server runs locally on port 8000 by default. An alternative port can be provided as an option.
python3 manage.py runserver <optional_port_number>
When the development server is started on the default port, the project can be viewed in the browser at the URL: http://localhost:8000
.
The development server will reload whenever there are changes to the application code.
New Django projects have several apps installed by default such as the admin panel and authentication.
INSTALLED_APPS = [# ... Other pre-installed apps"myapp.apps.MyappConfig"]
New apps are made with the startapp
command.
python3 manage.py startapp <name_of_app>
New Django apps must be added to settings.py in the INSTALLED_APPS
list in order for the project to recognize them.
INSTALLED_APPS = [# ... Other pre-installed apps"myapp.apps.MyappConfig"]
URLs are configured in URLconfig file, urls.py.
urlpatterns = [("", include("app.urls"))]
View functions are mapped to URLs inside urls.py.
urlpatterns = [path('', views.home, name="home")]
The migrate
command will update database models for projects installed in INSTALLED_APPS
.
python3 manage.py migrate
URLs are created using the path()
function which takes three arguments— the route, the view function, and an optional name.
path("", views.home, name="home")
Templates should be namespaced by creating a nested folder structure to avoid name conflicts between apps.
A response to a web request is given in a HttpResponse
object, which can be anything from HTML to an image.
def myView(request):return HttpResponse("Here is my response")