Django Official Documentation 1.6 study notes-Write your first Django program

Source: Internet
Author: User

Operating Environment centos6.5 django1.6 python2.7.8

Python-c "Import Django;print djang.get_version ()" or Django. VERSION

  1. To create a Django project:

    django-admin.py Startproject MySite

    The directory structure is as follows:

    mysite/# # #这个名字对django命名成什么都没关系.

    manage.py # # #操作你项目的命令行工具

    myite/# # #真正的django项目包, need to import the contents of this name

    __init__.py # # #把这个包变成一个朋友谈话哦能包

    settings.py # # #本django项目的配置相关

    urls.py # # #本django项目的url声明

    wsgi.py # # #于wsgi项匹配的WEB服务器的切入点

  2. Use of the development server (default is Port 8000)

    Python manage.py runserver 8080

    Python manage.py runserver 0.0.0.0:8080

  3. Database settings:

    Set in settings.py, Django defaults to the SQLite database

    Python manage.py syncdb Create a database table that does not exist in the database because Django comes with some apps that need to create the tables after the project is created

  4. What is the difference between prijects and app?

    What the app does for Web apps

    Project is a collection of many apps and configurations in a Web site

    An app can be used by a number of projects to include

    A project can contain a number of apps

  5. Create a Django App

    Pyrhon manage,py Startapp Polls

    The directory is as follows:

    polls/

    __init__.py

    admin.py

    models.py

    tests.py

    views.py

  6. Edit app entity class models.py (the first step in app development ...) The first step in an object-oriented language is to estimate it all.

    From django.db import Models

    Class Poll (models. Model):

    Question = models. Charfield (max_length=200)

    Pub_date = models. Datetimefield ("date published")

    def was_published_recently (self):

    return self.pub_date >= Timezone.now ()-Datetime.timedelta (Days=1)

    #使用unicode, because the Django entity class uses Unicode in python2.7.8 by default

    def __unicode__ (self):

    Return self.question

    Class Choice (models. Model):

    Poll = models. ForeignKey (Poll)

    Choice_text = models. Charfield (max_length=200)

    Votes = models. Integerfield (default=0)

    def __unicode__ (self):

    Return Self.choice_text

  7. Install the app because the Django app is Plug and play, so you can use one app in multiple projects, or you can publish apps because they don't have to do a given installation.

    Install the app in settings.py

    Installed_apps= (

    ' Polls ',

    )

  8. Displays the SQL statement that will be printed (does not execute the SQL statement) Python manage.py SQL polls

    Python manage.py syncdb

  9. Python manage.py shell into the Python shell to perform related database operations on entity classes

  10. http://localhost:8000/admin/into admin app

    Admin.site.register (Poll) tells the admin Poll this entity class class has an admin interface

  11. Class Polladmin (admin. Modeladmin)

    Fields = [' pub_date ', ' question '] #对admin的前台进行重新排序

    Admin.site.register (Poll,polladmin)

  12. class polladmin (admin. Modeladmin):

        fieldsets = [#将实体类前台form的元素是否放在一个field标签中

            (None, {' Fields ': [' question ']}), # The first element is a name, the second element is the entity class name

            (' Date Information ', {' Fields ': [' pub_date '], ' classes ': [' Collapse ']}, #collaps: fieldset whether the drop-down hides

       ]

    admin.site.register (poll,polladmin)

  13. class chiceinline (admin. Stackedinline): #admin. Tabularinlin, more compact ways to add

        model = Choice

        extra = 3 #在创建Poll的时候, create 3 choice options, auto-associate foreign key

    class polladmin (admin. Modeladmin):

        fieldsets = [

            (none,{' Fields ': [' question ']}),

            (' Date information ', {' Fields ': [' pub_date '], ' classes ': [' Collapse ']}),

       ]

        inlines = [Choiceinline]

    admin.site.register (poll,polladmin)

    #在页面的最后, + Add Anthon Choice

  14. Display Properties:

    Class Polladmin (admin. Modeladmin):

    List_display = (' question ', ' pub_date ') #将实体类中的两个属性进行展示

  15. Show Properties and Methods

    Class Polladmin (admin. Modeladmin):

    List_display = (' question ', ' pub_date ', ' was_published_recently ') #展示两个属性和实体类中一个方法的值

  16. Add Filter Change List page

    Class Polladmin (admin. Modeladmin):

    List_filter = [' pubdate ']

  17. Add a fuzzy query

    Class Polladmin (Modelsadmin):

    Search_fields = [' question '] #按此字段进行查询村, can add multiple, database query using like

  18. Personalize your project template

    Create a/template,templat under the project directory

    /mysite/settings.py and open Template_dirs setting:

    Template_dirs = [Os.path.join (base_dir, ' templates ')]

  19. Modify the App Admin template

    Under Templates This folder, create the Admin folder, copy the Django source admin/base_site.html to the folder

    Then look for changes to the content you want to modify.

  20. If you cannot find the source of Django on your machine, please run the following command:

    Python-c "Import Sys;sys.path=sys.path[1:];import django;print (django.__path__)"

  21. All admin templates can be overwritten, like overwrite base_site.html, copy them from the source bundle into your own directory, and make changes

  22. Personalization Admin Index page: slightly

  23. How did Django find its tempaltes?

    Django can look for template files from many places, depending on your tempalte-loader settings, but the most basic way is to use template_dirs settings

    Tempalte_dirs = (

    "/home/html/templates/lawrence.com",

    "/home/html/templates/default",

    )

    Your template files can be put anywhere you want, as long as your Web server can read them. You can use any suffix. txt. html, or no extension. Note that these paths require the use of a Linux-style forward slash, even under windows

    Djago.template.loader has two functions to load a template from a file:

    1,get_template (TEMPLATE_NAME): Returns a compiled template whose name is a given name (a template object), or raises if it does not exist Django.template.TemplateDoesNotExist

    2,select_template (template_name_list): Like Get_template (), just use a list of template names, which in this list returns the first existing template.

    Locate the file according to the Template_dirs's configured path order, or stop the lookup if it finds an existing template.

    Using subdirectories:

    It is best to organize your templates in a subdirectory in the template directory. Habit is a subdirectory of an app

    To load a template from a subdirectory, just use shorthand to do so, like this:

    Get_tempalte (' news/story_detail.html ')

    Combined with your above template_dirs configuration, the following template may be loaded:

    /home/html/templates/lawrence.com/news/story_detail.html

    /home/html/templates/default/news/story_detail.html

  24. Type of loader:

    By default, Django uses a file-based template loader, but Django has other loaders that know how to load templates from other resources

    Some of these default environments are invalidated, and you can set template_loaders to make them effective, tempalte_loaders should be a tuple of strings, each string represents a template loader class, and the following is a Django-brought template loader:

    Django.template.loaders.filesystem.Loader

    Class filesystem. Loader

    Loads the template from the file system, based on the configuration of the template_dirs. The default is valid.

    Django.template.loaders.app_directories. Loader

    Class App_directories. Loader

    Loads the Django Apps template from the file system. For each app installed in the Installed_apps, this loader looks for a subdirectory of the template

    , if the directory exists, Django will look for templates in this directory.

    For example:

    Installed_apps = (' Myject.polls ', ' myject.music ')

    Then Get_template (' foo.html ') will be found in the following folder in the following order:

    /path/to/myproject/polls/templates/

    /path/to/myproject/music/templates/

    and use the first found template to find it.

    The order of the apps installed in Installed_apps is critical if you want to personalize Django Admin in Myproject.polls using your own admin/base_ Site.html, you must guarantee your myprojrct.polls order before django.contrib.admin.

    This loader is optimized for the first time it is introduced, and it caches a list of which Installed_apps packages have template subdirectories.

    This loader is valid by default.

    Django.template.loaders.eggs.Loader

    Class eggs. Loader

    Much like the app_directories template loader, but this loader is loaded from the Python eggs instead of the file system.

    The default loader is not valid.

    Django.template.loaders.cached.Loafer

    Class cached. Loader

    By default, the template system will read and compile them when the template needs to be rendered, although the Django template system is very fast, and the overhead of reading and compiling the template increases.

    The cache loader is a class-based loader that should be overwritten when you configure a column of other loaders. The wrapper loader is used to locate the unknown template that was encountered at one time. The cache loader remembers this compiled template. The cached template is returned when the subsequent request requires the same template to be loaded. (There may be a problem with the translation)

    The cached template loader is a class-based loader so you configure with a list of other loaders that it should wrap. The wrapped loaders is used to locate unknown templates when they is first encountered. The cached loader then stores the compiled Template in memory. The cached templateinstance is returned for subsequent requests to load the same template.

    Like what:

    Template_loaders= (

    (' Django.template.loaders.cached.Loader ', (

    Django.template.loaders.filesysytem.Loader ',

    ' Django.template.loaders.app_directories. Loader ',

    )),

    )

    Cache loader is not valid by default

    Django uses the template loader in the order of template_loaders settings, and he uses each loader to know that a match is found.

  25. In Django, Web pages and other content are attempted to be sent, an attempt is made to be represented by a simple Python function or method, and Django chooses an attempt to process by checking the URL of the request.

    You may have encountered some similar url "me2/sites/dirmod.asp?sid=&type=gen&mod=core+pages&gid=a6cd4967199a42d9b65b1b" while surfing the internet, You'll be pleased that Django has a more elegant URL than that.

    In order for a URL to match the view, Django uses ' Urlconfs ', a urlconf match urlpatterns to the view

    From django.http import HttpResponse

    def index (Request):

    Return HttpResponse ("Hello,world. You is at the poll index ")

    In Django, this is probably the simplest view. To access the view, we need to match it to the URL and we need to urlconf

    To create a urlconf in the polls directory, I create a file named urls.py. Your app directory should look like this:

    polls/

    __init__.py

    admin.py

    models.py

    tests.py

    urls.py

    views.py

    The polls/url.py file contains the following code:

    From Django.conf.urls import Patterns,url

    From polls import views

    Urlpatterns = Patterns ("',

    URL (r ' ^$ ', views.index,name= ' index ')

    The next step is to point to the Polls.urls module in root urlconf. Insert an include () in mysite/urls.py

    From Django.conf.urls import Patterns,include,url

    From Django.contrib Import admin

    Admin.autodiscover ()

    Urlpatterns = Patterns ("',

    URL (r ' ^polls/', include (' Polls.urls ')),

    URL (r ' ^admin/', include (Admin.site.urls)),

    )

    Now that you have connected the index view to urlconf and run http://localhost:8000/polls/on your browser, you will see:

    Hello, world. You ' re at the poll index.

    The URL () function has four parameters, two are required (Regex view), two are optional (kwargs,name), which is worth recalling the effect of these parameters:

    Regex: A regular expression used to match the syntax of a string format. Django starts with the first regular expression, more than the URL of the request, knowing that the match is successful

    Note: The regular expression does not match the GET and post parameters or the domain name.

    In fact, you don't have to be proficient in regular expressions, because you just need to know the simple format. In fact, complex regular expressions may have poor lookup performance. So you can't use the full functionality of the regular expression.

    Finally, a performance tip: These regular expressions are compiled when the urlconf module is loaded for the first time.

    View: When Django finds a matching regular expression, it accesses the corresponding view function, which takes HttpRequest as the first parameter and any other parameters that are captured from the regular expression. If the regular expression uses simple captures, the value is passed as the positional parameter, and if the named captures is used, the value is passed as the keyword argument.

    Kwargs: Random keyword parameters can be passed to the target view in the keyword, in this tutorial we will not use this feature of Django

    Name: Name your URL so that you can explicitly refer to it elsewhere, especially in templates. This powerful feature allows you to make global changes to the project's Urlpatterns, when you can only modify one file at a time.

  26. Add more views to polls/views.py

    def detail (request,poll_id):

    Return HttpResponse (' Looking at poll%s '% poll_id)

    def results (request,poll_id):

    Return HttpResponse (' Looking at the results of poll%s '% poll_id)

    def vote (request,poll_id):

    Return HttpResponse ("You is voting on poll%s"% poll_id)

    Add a new view to the polls.urls.py file

    From Django.conf.urls import Patterns,url

    From polls import views

    Urlpatterns = Patterns ("',

    #ex:/poll/

    URL (r ' ^$ ', views.index,name= "index"),

    #ex:/poll/5/

    URL (r ' ^ (? p<poll_id>\d+)/$ ', views.detail,name= ' detail '),

    #ex:/polls/5/reults/

    URL (r ' ^ (? p<poll_id>\d)/reults/$ ', views.results,name= "results")

    $ex:/polls/5/vote/

    URL (r ' ^ (? p<poll_id>\d+)/vote/$ ', views.vote,name= "vote"),

    )









Django Official Documentation 1.6 study notes-Write your first Django program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.