Django Basic - Part 1

2 minute read

MVT Pattern

Installation

Vertual Environment (conda environment)

Create conda env with name of django

$ conda create -n django

Install Django

Enter django env by:

$ conda activate django

install pip:

$ conda install pip

install django using pip:

$ pip install django

Make Django Project

make project:

$ django-admin startproject webproj

Run server:

$ python manage.py runserver

Success:

Make Django App

go to webproj dir:
db.qlite3, manage.py, webproj

$ django-admin startapp homepage

now:
db.qlite3, homepage, manage.py, webproj

View

dir - homepage/views.py:

from django.shortcuts import HttpResponse, render

# Create your views here.

def index(request):
    return HttpResponse("Hello World!")

dir - webproj/urls.py:

from django.contrib import admin
from django.urls import path
from homepage.views import index

urlpatterns = [
    path('', index),
    path('admin/', admin.site.urls),
]

dir - webproj/setting.py:

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

Admin Registration

dir - django-proj/webproj Migrate first:

$ python manage.py migrate

result:

Resigter Admin account:

$ python manage.py createsuperuser

login as admin:

Template

h1 header

dir - homepage/views.py:

def index(request):
    return HttpResponse("<h1>Hello World!</h1>")

result:

Render

render:
render(request, β€˜~.html’, context) 이런 ν˜•μ‹μœΌλ‘œ renderλ₯Ό μ‚¬μš©ν•΄μ„œ template에 contextλ₯Ό μ±„μ›Œλ„£μ–΄ ν‘œν˜„ν•œ κ²°κ³Όλ₯Ό HttpResponse 객체와 ν•¨κ»˜ returnν•˜λŠ” ν•¨μˆ˜λ‹€.

  1. make the html file as request in homepage/template dir
  2. input the html file to render input in homepage/views.py
  3. add template path to TEMPLATES’s β€˜DIRS’ variable in webproj/settings.py (using os module)

1. Make html file in homepage/template

dir - homepage/template/index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Python django example</title>
        
    </head>

    <body>
        <h1>Title</h1>
        <p>blah</p>
    </body>
</html>

2. Input html file to render

def index(request):
    # return HttpResponse("<h1>Hello World!</h1>")
    return render(request, 'index.html', {})

3. Add template path

to TEMPLATES’s β€˜DIRS’ variable in webproj/settings.py
(using os module)
webproj/setting.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "homepage","template")
            ],
        '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',
            ],
        },
    },
]

Django-template language in html

dir - homepage/views.py
input as dictionary

def index(request):
    num = 10
    return render(request, 'index.html', {"my_num":num})

Using double curly bracket.
get value by dict key:

<!DOCTYPE html>
<html>
    <head>
        <title>Python django example</title>
        
    </head>

    <body>
        <h1>Title</h1>
        <p>blah</p>
        <p> {{ my_num }} </p>
    </body>
</html>

result:

Template Filter

ex: length, upper, …

  1. Modify homepage/views.py
  2. Modify homepage/tempate/index.html
def index(request):
    name = "John"
    return render(request, 'index.html', {"my_name":name})
...
    <body>
        <h1>Title</h1>
        <p>blah</p>
        <p>{{ my_name|length }}</p>
    </body>
...

result:

Template Tag

...
    <body>
        <h1>Title</h1>
        <p>blah</p>
        <p>{{ my_name|length }}</p>
        {% tag ... %}
        {% endtag ... %}
    </body>
...  

for tag

for tag:

...
    <body>
        <h1>Title</h1>
        <p>blah</p>
         {% for elem in my_lst %} 
            <p>{{elem}}</p>
         {% endfor %} 
    </body>
...

result:

if tag (if not)

if tag exercise return odd elements:

...
    <body>
        <h1>Title</h1>
        <p>blah</p>
         {% for elem in my_lst %} 
             {% if not elem|divisibleby:"2" %} 
                <p>{{elem}}</p>
             {% endif %} 
         {% endfor %} 
    </body>
...
  • if and if not is the same as python.
  • Must close the tag
  • using filter with variable(in this case elem)

ref:

django-mvt image: https://butter-shower.tistory.com/49
django render official: https://docs.djangoproject.com/ko/1.11/intro/tutorial03/

Leave a comment