Django is a powerful structure written with and using all the functionality of the Python programming language to create commercial and home websites of varying complexity. Django is an open source project that supports the implementation of the most popular packages and Python tools.
This beginner’s guide will explain you how to design a Django website by using a programming language.
We can create a full-fledged end-user web sites from scratch using Django with extensive administration and visualization. Many of the most modern and popular frameworks and libraries can be implemented using Django — Bootstrap, Angular, Vuejs, Backbone or others. Django, based on the MVC (Model-View-Controller) paradigm, has a default database — SQLite (lightweight DB), has a graphical administrator interface by default, which makes Django a convenient tool for creating and managing websites with minimal programming experience.
To create the first Django project, we need to install the Django and related packages (for additional functionality). You should also have Python installed. The best toolkit for Python and the working environment is Anaconda (recommended for installation). Django is available on pip. Run it with your terminal:
> pip install Django
> pip install django-imagekit
imagekit — associated with Django useful package for working with images. Also, you can find packages Django-CMS (content management system), Django-Bootstrap, additional packages for work with files, implementation of js-editors, translation, e-mail and much more. Now you have installed Django and basic libraries to build your first Django project.
To get started with creating the first Django website project, we need to create a new folder, for example, “WEB”, then open terminal or command line and type:
Let’s start the standard SQLite database for this project. To do this, we must go to the first Web_Site folder with the file manage.py:
> cd /Path/to/the/folder/WEB/
> django-admin startproject Web_Site
In the WEB folder you can see the following structure:
WEB Web_Site Web_Site __init__.py settings.py urls.py wsgi.py manage.py
Let’s start the standard SQLite database for this project. To do this, we must go to the first Web_Site folder with the file manage.py:
> cd /Path/to/the/folder/WEB/Web_Site
> python manage.py migrate
Now create an administrator and fill in the information:
> python manage.py createsuperuser
Create a new “Web_SiteTemps” folder in the first Web_Site folder for the administrator page template. In this folder, create a new folder called “admin”. Copy the base_site.html file from the installed Django package into this new “admin” folder. The path to base_site.html looks like: /Path/to/Anaconda/Lib/site-packages/django/contrib/admin/templates/admin/
This is the contents of base_site.html. We can customize something and, if necessary, add an additional style.
{% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Web_Site Admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Web_Site Administrator') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %}
The directory tree of the new project:
WEB Web_Site Web_SiteTemps admin base_site.html Web_Site __init__.py settings.py urls.py wsgi.py manage.py
The first project is created, now we need to create and connect the first Django application that will be used with this project. To create a run terminal/cmd application with the command:
> cd /Path/to/the/folder/WEB/Web_Site
> python manage.py startapp Web_App
Let’s configure the directory tree for the new Django application and add several folders for easy customization. Creating new folders in the Web_App directory — “media”, “static”, “Web_AppTemps” and new file URLs.py. In the static, media and Web_AppTemps folders, new “Web_App” folders are created. This is necessary for the correct search of the Django project path. The structure of the project catalog now looks like this:
WEB Web_site Web_App media Web_App migrations static Web_App Web_AppTemps Web_App __init__.py admin.py apps.py models.py tests.py urls.py views.py Web_SiteTemps admin base_site.html Web_Site __init__.py settings.py urls.py wsgi.py manage.py
Now create the home.html file for the web page and put these files in the Web_AppTemps/Web_App folder and the style.css file for styling in the static/Web_App folder. And create the Files folder in media/Web_App, if in the future we will download files and other media. A simple home.html file:
<!DOCTYPE html> <html lang="en"> {% load staticfiles %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" media="all" type="text/css" href="{% static 'Web_App/style.css' %}" /> <title>WEB SITE</title> </head> <body> <div class="element"> <p>Text</p> </div> <div class="element"> <p>Images</p> </div> <div class="element"> <p>Video</p> </div> <div class="element"> <p>Apps</p> </div> </body> </html>
And adding to the style.css file:
body { /* parent */ background-color: rgba(0, 41, 59, 1); margin: 0; width: 100%; height: auto; } .element { /* body */ float: left; width: 25%; height: 65%; padding-top: 5%; padding-right: 1%; padding-left: 1%; padding-bottom: 5%; margin-top: 2.5%; margin-right: 0%; margin-left: 15%; margin-bottom: 2%; background-color: rgba(1, 255, 217, 0.3); border-style: solid; border-left-width: 2px; border-right-width: 2px; border-top-width: 0px; border-bottom-width: 0px; border-radius: 1px; border-color: rgba(1, 255, 255, 1); } .element p { /* element */ width: 100%; height: auto; font: 5vw Open, sans-serif; text-align: center; color: rgba(0, 230, 255, 1); }
Project structure:
WEB Web_site Web_App media Web_App Files migrations static Web_App style.css Web_AppTemps Web_App home.html __init__.py admin.py apps.py models.py tests.py urls.py views.py Web_SiteTemps admin base_site.html Web_Site __init__.py settings.py urls.py wsgi.py manage.py
To create a function that will call our web page, we open the file
Web_App/views.py and add the following:
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'Web_App/home.html')
We need to configure the URL of the project and the application. First, open the Web_Site/urls.py file and change this:
"""Web_Site URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Web_App.urls', namespace="Web_App")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns()
Open Web_App/urls.py and put it in an empty file:
"""Web_App URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^home$', views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns()
additional imports will not be used in this example, but these tools are convenient and in the future, they can be very useful.
The file “settings.py” is the main file for configuring the Django project and additional applications. We can choose here how this project will work. Let’s change this file for our first site.
Web_Site/settings.py
""" Django settings for Web_Site project. Generated by 'django-admin startproject' using Django 1.11.1. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'g$8r#9oddc$3udgb7_90j#$u1nax06#5@2*w8((=84#)_v%(tg' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Web_App', # adding the application 'imagekit', # adding library for working with images ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Web_Site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, r'C:\Users\Люда\Desktop\WEB\Web_Site\Web_SiteTemps'), # Change first part of this path on Your path to the /WEB folder, # for linux change slash '\' to '/' os.path.join(BASE_DIR, r'C:\Users\Люда\Desktop\WEB\Web_Site\Web_App\Web_AppTemps')], # Change first part of this path on Your path to the /WEB folder, # for linux change slash '\' to '/' 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Web_Site.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_ROOT = r'C:\Users\Люда\Desktop\WEB\Web_Site\Web_App\static\Web_App' # Change first part of this path on Your path to the /WEB folder, # for linux change slash '\' to '/' STATIC_URL = '/static/' MEDIA_ROOT = r'C:\Users\Люда\Desktop\WEB\Web_Site\Web_App\media\Web_App' # Change first part of this path on Your path to the /WEB folder, # for linux change slash '\' to '/' MEDIA_URL = '/media/'
To complete this work, we need to take the following steps. First, open the terminal and change our directory to the folder with the file manage.py inside:
> cd /Your/Path/to/the/WEB/Web_Site
then:
> python manage.py migrate
run the command to initialize the application:
> python manage.py makemigrations Web_App
These are standard procedures and a call to initiate changes to the project. Also, if you use the website in production mode, you can run collectstatic command to collect static files. Then start the default Django server with an explicit port number or use it by default (Hint — ports up to 1000 require superuser privileges):
> python manage.py run server 1414
Now your server is running on the host 127.0.0.1 (localhost) and port 1414. If you open your browser and paste it into the search tab http://127.0.0.1:1414/, it will open the following web page:
If you enter http://127.0.0.1:1414/admin, this open administration page and after logging on you will see a set of administration tools:
Hope, this basic Django tutorial makes you understand the creation of web applications and websites.
As you can see, you do not need a lot of time and programming experience to run your own website. Django is a powerful tool for creating your own web applications and websites. This example describes the first steps, just to create in development mode, but if you decide to go into production mode — it will not be more difficult than before. All you need is to choose the server for this. You can deploy the Django project using Apache and mod_wsgi, with Nginx or with other servers. The website operates in production mode using ports 80 (http) and 443 (https), which are required superuser privileges to start the server with these port numbers. You can also connect other databases, such as PostgreSQL. Django gives you the ability to use additional packages and Python tools like numpy, scikit-learn and many other problems with compatibility with the Python programming language.
Leave a Reply
Your email address will not be published. Required fields are marked *