Wednesday, December 12, 2012

The Django Notes Chapter 1 - 4

python xxx/xxx/ startproject mysite (linux

D:\ZDY\Working0> python \ZDY\Python\Scripts\ startproject quality startproject mysite
  • A file required for Python to treat the mysite directory as a package (i.e., a group of Python modules). It’s an empty file, and generally you won’t add anything to it.
  • A command-line utility that lets you interact with this Django project in various ways. Type python help to get a feel for what it can do. You should never have to edit this file; it’s created in this directory purely for convenience.
    • (subcommand, reset, cleanup, sql, sqlclear etc.)
  • Settings/configuration for this Django project. Take a look at it to get an idea of the types of settings available, along with their default values.
    • DATABASES = {
      •     'default': {
        •         'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
          •         'NAME': '',                      # Or path to database file if using sqlite3.
            •         'USER': '',                      # Not used with sqlite3.
              •         'PASSWORD': '',                  # Not used with sqlite3.
                •         'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
                  •         'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
                    •     }
                      • }
                      • The URLs for this Django project. Think of this as the “table of contents” of your Django-powered site. At the moment, it’s empty.
                      python runserver

                      NOTICE: must import the view function into

                      urlpatterns = patterns('',
                      ('^hello/$', hello),
                      ('^time/$', current_datetime),
                      ('^another_time/$', current_datetime)

                      ^ start with, $ end with
                      tuple inside the tuple

                      Django Error Message

                    • At the top of the page, you get the key information about the exception: the type of exception, any parameters to the exception (the "unsupported type" message in this case), the file in which the exception was raised, and the offending line number.
                    • Under the key exception information, the page displays the full Python traceback for this exception. This is similar to the standard traceback you get in Python’s command-line interpreter, except it’s more interactive. For each level (“frame”) in the stack, Django displays the name of the file, the function/method name, the line number, and the source code of that line.
                      Click the line of source code (in dark gray), and you’ll see several lines from before and after the erroneous line, to give you context.
                      Click “Local vars” under any frame in the stack to view a table of all local variables and their values, in that frame, at the exact point in the code at which the exception was raised. This debugging information can be a great help.
                    • Note the “Switch to copy-and-paste view” text under the “Traceback” header. Click those words, and the traceback will switch to a alternate version that can be easily copied and pasted. Use this when you want to share your exception traceback with others to get technical support – such as the kind folks in the Django IRC chat room or on the Django users mailing list.
                      Underneath, the “Share this traceback on a public Web site” button will do this work for you in just one click. Click it to post the traceback to, where you’ll get a distinct URL that you can share with other people.
                    • Next, the “Request information” section includes a wealth of information about the incoming Web request that spawned the error: GET and POST information, cookie values, and meta information, such as CGI headers. Appendix G has a complete reference of all the information a request object contains.
                      Below the “Request information” section, the “Settings” section lists all of the settings for this particular Django installation. (We’ve already mentioned ROOT_URLCONF, and we’ll show you various Django settings throughout the book. All the available settings are covered in detail in Appendix D.)

                      TypeError at /time/plus/10/

                      unsupported type for timedelta hours component: unicode
                      Request Method:GET
                      Request URL:
                      Django Version:1.4.2
                      Exception Type:TypeError
                      Exception Value:
                      unsupported type for timedelta hours component: unicode
                      Exception Location:D:\ZDY\Working0\mysite\mysite\ in hours_ahead, line 17
                      Python Executable:D:\ZDY\Python\python.exe
                      Python Version:2.7.3
                      Python Path:
                      Server time:Wed, 12 Dec 2012 11:09:24 +0800

                      Traceback Switch to copy-and-paste view

                      • D:\ZDY\Python\lib\site-packages\django\core\handlers\ in get_response
                        1.                         response = callback(request, *callback_args, **callback_kwargs)
                      • D:\ZDY\Working0\mysite\mysite\ in hours_ahead
                        1.     return HttpResponse(html) 
                        3. def hours_ahead(request, offset):
                        4.     '''ry:
                        5.         offset = int(offset)
                        6.     except ValueError:
                        7.         raise Http404()'''
                        1. + datetime.timedelta(hours=offset)
                        1.     html="<html><body>In %s hour(s), it will be %s.<body></html>" %(offset, dt)
                        2.     return HttpResponse(html)

                      Request information


                      No GET data


                      No POST data

                    • Template
                      1. write a template string 
                      2. create a Template object
                      3. create aContext
                      4. call the render() method.
                      from django.template.loader import get_template
                      from django.template import Context
                      from django.http import HttpResponse
                      import datetime
                      {% if %} tags don’t allow and and or clauses within the same tag
                      The use of parentheses for controlling order of operations is not supported. If you find yourself needing parentheses, consider performing logic outside the template and passing the result of that as a dedicated template variable.

                      like bash scripting, There is no {% elif %} tag
                      {% if athlete_list %}
                          <p>Here are the athletes: {{ athlete_list }}.</p>
                      {% else %}
                          <p>No athletes are available.</p>
                          {% if coach_list %}
                              <p>Here are the coaches: {{ coach_list }}.</p>
                          {% endif %}
                      {% endif %}
                      {% for athlete in athlete_list reversed %}
                      {% endfor %}
                      nested for loop
                      {% for athlete in athlete_list %}
                          <h1>{{ }}</h1>
                          {% for sport in athlete.sports_played %}
                              <li>{{ sport }}</li>
                          {% endfor %}
                      {% endfor %}
                      {% for athlete in athlete_list %}
                          <p>{{ }}</p>
                      {% empty %}
                          <p>There are no athletes. Only computer programmers.</p>
                      {% endfor %}
                      There is no support for “breaking out” of a loop before the loop is finished. If you want to accomplish this, change the variable you’re looping over so that it includes only the values you want to loop over. Similarly, there is no support for a “continue” statement that would instruct the loop processor to return immediately to the front of the loop. (See the section “Philosophies and Limitations” later in this chapter for the reasoning behind this design decision.)

                      1. forloop.counter (start from 1)
                      2. forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be set to 0 the first time through the loop.
                      3. forloop.revcounter is always set to an integer representing the number of remaining items in the loop. The first time through the loop, forloop.revcounter will be set to the total number of items in the sequence you’re traversing. The last time through the loop,forloop.revcounter will be set to 1.
                      4. forloop.revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first time through the loop, forloop.revcounter0 will be set to the number of elements in the sequence minus 1. The last time through the loop, it will be set to 0.
                      5. forloop.last
                      6. forloop.first is a Boolean value set to True if this is the first time through the loop. This is convenient for special-casing:
                      {% for object in objects %}
                          {% if forloop.first %}<li class="first">{% else %}<li>{% endif %}
                          {{ object }}
                      {% endfor %}
                      {% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %}
                      Link1 | Link2 | Link3 | Link4
                      Favorite places:
                      {% for p in places %}{{ p }}{% if not forloop.last %}, {% endif %}{% endfor %}
                      matrix, table
                      {% for country in countries %}
                          {% for city in country.city_list %}
                              <td>Country #{{ forloop.parentloop.counter }}</td>
                              <td>City #{{ forloop.counter }}</td>
                              <td>{{ city }}</td>
                          {% endfor %}
                      {% endfor %}
                      {% ifequal XXX YYY %} do something {% endifequal %}
                      {% ifnotequal XXX YYY %} do something {% endifnotequal %}

                      Template Loading

             and find the TEMPLATE_DIRS setting.
                      whew the relative path of template directory is mysite/templates (load the ROOT directory of template)
                      import os.path
                      TEMPLATE_DIRS = (
                          os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
                      #Do't forget to use ABSOLUTE paths, not relative paths
                      #Always use forward slashes, even on Windows.

                      render_to_response() <<<<<<<<<<<shortcuts

                      from django.shortcuts import render_to_response
                      import datetime
                      def current_datetime(request):
                          now ={%
                          return render_to_response('current_datetime.html', {'current_date': now})

                      Template Inheritance

                      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
                      <html lang="en">
                          <title>{% block title %}{% endblock %}</title>
                          <h1>My helpful timestamp site</h1>
                          {% block content %}{% endblock %} ABSTRACTION
                          {% block footer %}
                          <p>Thanks for visiting my site.</p>
                          {% endblock %}
                      {% extends "base.html" %}
                      {% block title %}The current time{% endblock %}
                      {% block content %}
                      <p>It is now {{ current_date }}.</p>
                      {% endblock %}
                      {% extends "base.html" %}
                      {% block title %}Future time{% endblock %}
                      {% block content %}
                      <p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
                      {% endblock %}

                      THREE-LEVEL APPROACH for template inheritance
                      You can use as many levels of inheritance as needed. One common way of using inheritance is the following three-level approach:
                      1. Create a base.html template that holds the main look and feel of your site. This is the stuff that rarely, if ever, changes.
                      2. Create a base_SECTION.html template for each “section” of your site (e.g., base_photos.html and base_forum.html). These templates extend base.html and include section-specific styles/design.
                      3. Create individual templates for each type of page, such as a forum page or a photo gallery. These templates extend the appropriate section template.

                      Primitive Data Structure in Template

                      • Dictionary lookup (e.g., foo["bar"])
                      • Attribute lookup (e.g.,
                      • Method call (e.g.,
                      • List-index lookup (e.g., foo[2])
                      • List-index lookup alternative (e.g. foo.2)



                      No comments:

                      Post a Comment