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

10. Django 1.8 Server Build - CentOS 7 hosted on VPS - Views 2 (home page and more templates)

django.png




Bookmark and Share





bogotobogo.com site search:




Note

In previous chapter (9. Django 1.8 Server Build - CentOS 7 hosted on VPS - Views (templates and css)), we learned about views via views.py, urls.py, templates, and css.

view2-tree1.png




Home page

We have http://djangotest.sfvue.com/admin and http://djangotest.sfvue.com/cars/, however, we do not have our home page yet:

NoHomePage.png

Here is the modified djangotest/urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
   url(r'^$', 'car.views.index'),
   url(r'^cars/$', 'car.views.CarsAll'),
]


car/views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext
from car.models import Car

def CarsAll(request):
    cars = Car.objects.all().order_by('name')
    context = {'cars': cars}
    return render_to_response('carsall.html',context, context_instance=RequestContext(request))

def index(request):
    return render_to_response('index.html')

The render_to_response(template_name) renders a given template and returns an HttpResponse object with that rendered text.



car/templates/index.html:

{% extends "base.html" %}
{% block content %}
    <a href="cars/">View the Cars list</a>
{% endblock %}


http://djangotest.sfvue.com/ page has a link on the top-left:

link-to-index.png

If we click the link, we get http://djangotest.sfvue.com/cars/ page:

linked-index-page.png



How Django renders templates

Before we go deep into templates world, let's look at how template gets rendered (The first views).

Django templates are normal Python objects whose constructor expects a string. The placeholders are replaced with the values from a context object.

The following example shows how a dictionary can be used as data structure:

$ python manage.py shell
Python 2.7.5 (default, Jun 17 2014, 18:11:42)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.template import Context, Template
>>> t = Template('My name is {{ person.first_name }}.')
>>> d = {'person': {'first_name': 'bogotobogo'}}
>>> t.render(Context(d))
u'My name is bogotobogo.'

We can use a Python object as data structure:

>>> class Person: pass
...
>>> p = Person()
>>> p.first_name = 'bogotobogo'
>>> c = Context({'person': p})
>>> t.render(c)
u'My name is bogotobogo.'
>>>

Lists can be used as well:

>>> t = Template('First article: {{ articles.0 }}')
>>> c = Context({'articles': ['bread', 'eggs', 'milk']})
>>> t.render(c)
u'First article: bread'
>>>




templates/carsall.html

We want to list one item per line instead of just printing out all in one line:

{% extends "base.html" %}
{% block content %}
    <div id="carslist">
        {% for car in cars %}
        <p><a href="/cars/{{ car.slug }}">{{ car }}</a></p>
        {% endfor %}
    </div>
{% endblock %}

Note that we used {{ variable }} forms for {{ car.slug }} and {{ car }}. When the template engine encounters a variable, it evaluates that variable and replaces it with the result.


cars-links.png

But if we click the link, we get 404 error:

specific-not-found.png

Let's work on displaying specific car item.





car/views.py

We want to make the broken link in the previous section.

from django.shortcuts import render_to_response
from django.template import RequestContext
from car.models import Car

def CarsAll(request):
    cars = Car.objects.all().order_by('name')
    context = {'cars': cars}
    return render_to_response('carsall.html',context, context_instance=RequestContext(request))

def index(request):
    return render_to_response('index.html')

def SpecificCar(request, carslug):
    c = Car.objects.get(slug=carslug)
    context = {'car': c}
    return render_to_response('singlecar.html')

We need to modify urls.py.





djangotest/urls.py

Open djangotest/urls.py and add an url for the specific car item:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
   url(r'^$', 'car.views.index'),
   url(r'^cars/$', 'car.views.CarsAll'),
   url(r'^cars/(?P<carslug>.*)/$', 'car.views.SpecificCar'),
]

In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern), where name is the name of the group and pattern is some pattern to match.

It passes a variable carslug to car.views.SpecificCar.





templates/singlecar.html

{% extends "base.html" %}
{% block content %}
    <div id="singlecar">
        <p>Name: {{ car }}</p>
        <p>Locality: {{ car.locality }}</p>
        <p>Make: {{ car.make }}</p>
    </div>
{% endblock %}

Now, if we click the link we get a page for the single car item:

single-item.png

Let's make a minor change for the display of locality. In other words, we want "Import" instead of just "I". To see what function we can use, let's use shell:

>>> from car.models import Car
>>> c = Car.objects.get(name='M6 Coupe')
>>> c
<Car: M6 Coupe>
>>> c.slug
u'BMW-M6-F12-Coupe-2015'
>>> dir(c)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', 
'__getattribute__', '__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_base_manager',
 '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', 
'_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model',
 '_check_ordering', '_check_swappable', '_check_unique_together', '_default_manager', '_deferred', '_do_insert', '_do_update',
 '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', 
'_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', 
'_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'date_error_message', 'delete', 'description', 'from_db', 
'full_clean', 'get_deferred_fields', 'get_locality_display', 'id', 'locality', 'make', 'make_id',
 'name', 'objects', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'slug', 
'unique_error_message', 'validate_unique']
>>> c.get_locality_display()
u'Import'
>>>

So, let's go back to templates/singlecar.html, and modify it:

{% extends "base.html" %}
{% block content %}
    <div id="singlecar">
        <p>Name: {{ car }}</p>
        <p>Locality: {{ car.get_locality_display }}</p>
        <p>Make: {{ car.make }}</p>
    </div>
{% endblock %}

Note that we're not using "()" for get_locality_display in the templates.

Now, if the page is display "Import" rather than just "I":

Import.png



Getting cars from a specific Makes

Let's get the list of cars from a specific Makes.

Open up car/views.py, and we filter our cars from a given Makes

from django.shortcuts import render_to_response
from django.template import RequestContext
from car.models import Car
from car.models import Make

def CarsAll(request):
    cars = Car.objects.all().order_by('name')
    context = {'cars': cars}
    return render_to_response('carsall.html',context, context_instance=RequestContext(request))

def index(request):
    return render_to_response('index.html')

def SpecificCar(request, carslug):
    c = Car.objects.get(slug=carslug)
    context = {'car': c}
    return render_to_response('singlecar.html', context, context_instance=RequestContext(request))

def SpecificMake(request, makeslug):
    m = Make.objects.get(slug=makeslug)
    cars = Car.objects.filter(make=m)
    context = {'cars': cars}
    return render_to_response('singlemake.html', context, context_instance=RequestContext(request))

Then, urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
   url(r'^$', 'car.views.index'),
   url(r'^cars/$', 'car.views.CarsAll'),
   url(r'^cars/(?P<carslug>.*)/$', 'car.views.SpecificCar'),
   url(r'^makes/(?P<makeslug>.*)/$', 'car.views.SpecificMake'),
]

Then, car/templates/singlemake.html:

{% extends "base.html" %}
{% block content %}
    <div id="carslist">
        <h2>Cars from {{ cars.0.make }}</h2>
        {% for c in cars %}
        <p><a href="/cars/{{ c.slug }}/">{{ c }}</a></p>
        {% endfor %}
    </div>
{% endblock %}

Also, we need to make the make a link in car/templates/singlecar.html:

{% extends "base.html" %}
{% block content %}
    <div id="singlecar">
        <p>Name: {{ car }}</p>
        <p>Locality: {{ car.get_locality_display }}</p>
        <p>Make: <a href="/makes/{{ car.make.slug }}/">{{ car.make }}</a></p>
    </div>
{% endblock %}


M6-Convertibal-click.png

If we click on "M6 Convertible 2013", we get:

BMW-M6.png

Then, at the click Make BMW, we get the list of cars from that specific make:

Cars-from-BMW.png


Continued in 11. TinyMCE









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