BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

4. Hello World - Templates

django.png




Bookmark and Share





bogotobogo.com site search:




Note

Please allow me to digress here.

I've tried "Hello World" numerous times whenever I started learning something new. It's always good to have a feeling of "mission accomplished." But sometimes that was it, and I stopped there.

I'll show you here what can we do with Django if you stay firm.

The following pictures are from my forum site using Django (http://www.bogotobogo.com/dj/forums/).


Forum_Front.png

QtForum.png

Reply_Qt.png

Login_SESSION.png

As we can see from the pictures above, we'll be able to setup discussion pages with user registration. It may take couple of days or at most a week or two. If you have your domain, you can have forums/blogs under your full control.

Regarding the web services platform, I like Ruby On Rails mainly because it's MVC is crystal clear. Also, I've tried LaRavel 4 which is php based, it's good as well, and I think it has a potential to beat other php frameworks such as Symphony. With Ruby, I was able to deploy it using Heroku but not with my shared host service. LaRavel, I have yet to deploy it.

Anyway, I like Python, and I'm kind of biased toward to Django!





Dynamic Contents

So far, we created a project and made an app (HelloWorldApp). By modifying the url.py and views.py, we were able to get a very humble page on a local machine where the development version of server was running.

Let's create something more dynamic which produces "Hello world! from Bogo" by modifying the HelloWorldApp/views.py:

from django.http import HttpResponse
def foo(request):
    name = "Bogo"
    html = "<html><body>Hello World! from %s</body></html>" % name
    return HttpResponse(html)

The third line of code within the view constructs an HTML response using Python's "format-string" capability. The %s within the string is a placeholder, and the percent sign after the string means "Replace the %s in the preceding string with the value of the variable now."


HelloWorldfromBogo.png

As we can guess from the code above, any change to the design of the page (html) requires a change to the Python code and it's not a good idea to hard-code HTML directly in our views. It will be much cleaner and more maintainable to separate the design of the page from the Python code itself. We can do this with Django's template system, which we discuss in next section.





Basics of Templates

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).

A Django template is intended to separate the presentation of a document from its data. A template defines placeholders and various bits of basic logic (template tags) that regulate how the document should be displayed. Usually, templates are used for producing HTML.

Here is a sample from djangobook:

<html>
<head><title>Ordering notice</title></head>

<body>

<h1>Ordering notice</h1>

<p>Dear {{ person_name }},</p>

<p>Thanks for placing an order from {{ company }}. It's scheduled to
ship on {{ ship_date|date:"F j, Y" }}.</p>

<p>Here are the items you've ordered:</p>

<ul>
{% for item in item_list %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

{% if ordered_warranty %}
    <p>Your warranty information will be included in the packaging.</p>
{% else %}
    <p>You didn't order a warranty, so you're on your own when
    the products inevitably stop working.</p>
{% endif %}

<p>Sincerely,<br />{{ company }}</p>

</body>
</html>
  1. Any text surrounded by a pair of braces, {{ person_name }}, is a variable. This means "insert the value of the variable with the given name."
  2. Any text that's surrounded by curly braces and percent signs, {% if ordered_warranty %}, is a template tag. The definition of a tag is quite broad: a tag just tells the template system to "do something." This example template contains a for tag ({% for item in item_list %}) and an if tag ({% if ordered_warranty %}).
  3. A for tag works very much like a for statement in Python, letting us loop over each item in a sequence. An if tag acts as a logical "if" statement. In this particular case, the tag checks whether the value of the ordered_warranty variable evaluates to True. If it does, the template system will display everything between the {% if ordered_warranty %} and {% else %}. If not, the template system will display everything between {% else %} and {% endif %}. Note that the {% else %} is optional.
  4. The second paragraph of this template contains an example of a filter, which is the most convenient way to alter the formatting of a variable. In this example, {{ ship_date|date:"F j, Y" }}, we're passing the ship_date variable to the date filter, giving the date filter the argument "F j, Y". The date filter formats dates in a given format, as specified by that argument. Filters are attached using a pipe character (|), as a reference to Unix pipes.




Templates for Hello World

So far, we created a project and made an app (HelloWorldApp). By modifying the url.py and views.py, we were able to get a very humble page on a local machine where the development version of server was running.

As we already know, the html page has several invariants such as header or footer etc. So, we may want to have a template with our site design in it.


Let's go to the app directory (HelloWorldApp) and make templates directory:

$ cd HelloWorldApp
$ mkdir -p templates/helloDJ
$ touch templates/helloDJ/base.html

HelloWorldTemplateTreeA.png

Let's make the base.html as below:

<html>
  <head>
    <title>This is Hello World app!</title>
  </head>
  <body>
    <h1>Welcome to Django at bogotobogo.com</h1>
    {% block content %}
    {% endblock %} 
  </body>
</html>

Everything is a normal html except for the {% block %} part. Djangle template language provides us dynamic contents and something will happen in the block portion. Actually, Django equips us for tags, filters, and output.

Django first looks into settings for TEMPLATE_DIRS, and into app folders. This can be customized by setting TEMPLATE_LOADERS which default to :

('django.template.loaders.filesystem.Loader',
 'django.template.loaders.app_directories.Loader')




Template Inheritance

We may also want to create another template called home.html:

{% extends "helloDJ/base.html" %}
{% block content %}
{{ Testing }}
{{ HelloHello }}
{% endblock %}

This is an inheritance of the template. The extends block tag means home.html will be shown inside base.html. The two braces "{{" and "}}" are basically a print statement.

Our base.html will stay with little change throughout several html pages. But the extension will take any specifics of a certain page within the frame of the base.html. In other words, any block in home.html will show up in the same named block in base.html.


HelloWorldTemplateTreeB.png

The {{ HelloHello }} will output the variable HelloHello passed by the views. So, we need to go back and fix our views.py:

from django.shortcuts import render_to_response
def foo(request,):
    return render_to_response("helloDJ/home.html",
                               {"Testing" : "Django Template Inheritance ",
                               "HelloHello" : "Hello World - Django"})

Here, the HelloHello is a variable and it's a key for dictionary feed for the template. Django will take over and properly render a page for us:





Web App using Template Inheritance

Let's run the server:

python manage.py runserver

Now, we can run our first web application using template and template inheritance:


Browser_template.png









Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master