Django I

Serie of articles about developing a Full Django Web Site.


Conda

https://www.anaconda.com/rpm-and-debian-repositories-for-miniconda/

Install on Linux Debian

cd opt
mkdir conda
cd conda
curl https://repo.anaconda.com/pkgs/misc/gpgkeys/anaconda.asc | gpg --dearmor > conda.gpg
install -o root -g root -m 644 conda.gpg /etc/apt/trusted.gpg.d/

add this line to sources.list:

[arch=amd64] https://repo.anaconda.com/pkgs/misc/debrepo/conda stable main

Instead, we can execute this command which add the entry to sources.list.d

echo "deb [arch=amd64] https://repo.anaconda.com/pkgs/misc/debrepo/conda stable main" > /etc/apt/sources.list.d/conda.list

Install Conda:

apt-get install conda

Set PATH on Linux

Conda is installed into working directory, so it was installed into /opt/conda/

Steps to set the PATH on Linux.

  1. Change to your home directory.
    cd $HOME
    
  2. Open the .bashrc file.
    Add the following line to the file. Replace the JDK directory with the name of your java installation directory.

    export PATH=/opt/conda/bin:$PATH
    

    Save the file and exit.

  3. Use the source command to force Linux to reload the .bashrc file which normally is read only when you log in each time.
    source .bashrc
    

Create environment

test Conda:

$conda --v

create env:

$conda create --name MyDjangoEnv python=3.5

check envs:

$conda info --envs

To activate this environment, use:

source activate MyDjangoEnv

To deactivate an active environment, use:

source deactivate

Install Django

Install Django:

(MyDjangoEnv) $conda install django

Django

What is going to see here about how administrate a Django Web Site:

  • Setting up Projects and Applications
  • Creating Views and Mapping URLs
  • Using simple Templates and tags
  • Serving static media files

Setting up Projects and Applications

Create a working directory, for example, Django_workspace:

$ mkdir Django_workspace
$ cd Django_workspace

Before working with any aspect on Django, we must activate the virtual environment:

$ source activate MyDjangoEnv

Create the project:

(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace$ django-admin startproject first_project
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace$ cd first_project
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ ls
first_project  manage.py

Run the project the very first time:

(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sess
ions.
Run 'python manage.py migrate' to apply them.

March 24, 2019 - 16:58:40
Django version 2.1.1, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Copy the URL http://127.0.0.1:8000/ in a browser to check it works!

Now we create an application:

(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py startapp first_app

The files structure is how follow:

First Project Directories

Creating Views and Mapping URLs

Let’s create our first view, it would be called ‘Hello World’ view, for that we must edit the files:

first_project => settings.py, add into INSTALLED_APP list our app ‘first_app’

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first_app',
]

first_app => views.py =>

create the view itself:

from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello Word!")

first_project => urls.py, mapping the view:

from first_app import views

and add the view into the urlpatterns list:

urlpatterns = [
    path('', views.index, name="index"),
...

It is time to test:

$ cd first_project
antiax@debian:~/Desktop/Django_workspace/first_project$ source activate MyDjangoEnv
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py runserver
 Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sess
ions.
Run 'python manage.py migrate' to apply them.

March 28, 2019 - 18:16:18
Django version 2.1.1, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

and check in a browser the URL http://127.0.0.1:8000/

include

Let separate the urls mapping into each app, the general project file urls.py will refer those with include.

So, for example, for the URL dominio.org/first_app/… the mapping will be stored into first_app => urls.py

The first step will be create that file:

first_project/first_app/urls.py

from django.urls import path
from first_app import views

urlpatterns = [
    path('', views.index, name = "index"),
]

the file first_project/urls.py will mapping dominio.org/first_app/ to the views definided above.

first_project/first_project/urls.py

from django.conf.urls import include
urlpatterns = [
    ...
    path('first_app/', include('first_app.urls')),
    ...
]

The URLS http://127.0.0.1:8000/ and http://127.0.0.1:8000/first_app get the same result, because both refer the same view by different way. Using include will get more well organized our Apps mapping when we have more than one.

Using simple Templates and tags

Templates will contain the static parts of an html page, then there are template tags, which allow you to inject dynamic content
Django will be able to inject content into the HTML

to do our application can easily be ‘cross platform’ we have to dynamically generate the correct file path strings (DIR into setting.py use full path).

Step 1: create directory template under first_project root directory:

Templates Directory

Step 2: first_project/first_project/settings.py

TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        ...

Step 3: create the template under templates directory: templates/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>First App</title>
  </head>
  <body>
    <h1>Hello this is index.html!</h1>
    {{ insert_me }}
  </body>
</html>

Step 4: first_app/views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    my_dict ={'insert_me': 'Hello I am from views.py !'}
    return render(request, 'index.html', context=my_dict)

Step 4: test !!!!

antiax@debian:~/Desktop/Django_workspace/first_project$ source activate MyDjangoEnv
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py runserver

visit the URL http://127.0.0.1:8000/

Step 5: (NOTE) Separate out our templates by application:

first_app/views.py

def index(request):
    my_dict ={'insert_me': 'Now I am coming from first_app/index.html !'}
    return render(request, 'first_app/index.html', context=my_dict)

and reorganize the templates directory:

Templates Directory Reorganized

Serving static media files

1) create the directory ‘static’ as the same way we created the ‘templates’ directory UNDER MAIN PROJECT DIRECTORY:

Static Directory

2) link this directory to the project:

first_project => settings.py

STATIC_DIR = os.path.join(BASE_DIR,"static")
...
STATICFILES_DIRS = [
    STATIC_DIR,
]

3) Use static file tags into the templates files:

templates => first_app => index.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>First App</title>
  </head>
  <body>
    <h1>Hello this is index.html!</h1>
    {{ insert_me }}
    <h1>Hi, this is a picture of Django himself!</h1>
    <img src="{% static "images/django_guitar.jpg" %}" alt="No image to show!">
  </body>
</html>

4) Test:

antiax@debian:~/Desktop/Django_workspace/first_project$ source activate MyDjangoEnv
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py runserver

5) static CSS files:

create the directory ‘static/css’ and the file style.css

h1 {
  color: red;
}

6) insert the static tag into the template to link the CSS file:

<link rel="stylesheet" href="{% static "css/style.css" %}">

{% static “css/style.css” %} means under static directory locate the file css/style.css

7) test:

antiax@debian:~/Desktop/Django_workspace/first_project$ source activate MyDjangoEnv
(MyDjangoEnv) antiax@debian:~/Desktop/Django_workspace/first_project$ python manage.py runserver