1. Quick install guide

1.1   Install Python, it works with Python2.6, 2.7, 3.2, 3.3. All these version of Python include a lightweight database SQLite, so you don't need to setup a database

1.2   Remove any old versions of Django: if you are upgrading your installation of Django from a previous version, you will need to uninstall the old version before installing the new version

1.3   If you previously installed Django using python setup.py install, uninstalling is as simple as deleting the Django directory from your Python site-packages.

1.4   To find the directory you need to remove, you can run the following at your shell prompt(not the interactive Python prompt): python -c "import sys; sys.path = sys.path[1:]; import django; print(django.__path__)"

1.5   Install the Django code: install pip, and use “sudo pip install Django”(on Linux or Mac OS) or “pip install Django”(on Windows), or specific the version: “pip install Django==1.6.3”

1.6   Installing an official release manually: download the latest version, and use “python setup.py install”

1.7   Verifying: import Django, print Django.get_version()

  1. Creating a project: from the command line, cd into a directory where you want to store your code, then run the following command: django-admin.py startproject mysite  this will create a mysite directory in your current directory
  2. Note: you’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like Django or test
  3. The outer mysite/ root directory is just a container for your project. Its name doesn’t matter to Django. You can rename it to anything you like.
  4. Manage.py: A command-line utility that lets you interact with this Django project in various ways.
  5. The inner mysite/ ditrectory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it(e.g. mysite.urls)
  6. Mysite/__init__.py: an empty file that tells Python that this directory should be considered as Python package.
  7. Mysite/settings.py: Setting/configuration for this Django project.
  8. Mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
  9. Mysite/wsgi.py: an entry-point for WSGI-compatible web servers to serve your project.
  10. Change into the outer mysite directory, run the command python manage.py runserver, now that the server is running, visit http://localhost:8000 with your web browser. You’ll see “Welcome to Django” page.
  11. By default, the runserver command starts the development server on the internal IP at port 8080
  12. If you want to change the server’s port, pass it as a command-line argument. For instance, this commands starts the server on port 8000: pythin manage.py runserver 8000
  13. If you want to change the server’s IP, pass it along with the port, so to listen on all public IPs(useful if you want to show off your work on other computers), use: python manage.py runserver 0.0.0.0: 8000
  14. By default, the configuration(mysite/settings.py) uses SQLite.
  15. If you wish to use another database, change the following keys in the DATABASE’default’ item to match your database connection settings:

16.1            ENGINE – either ‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql_psycopq2’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’

16.2            NAME – the name of your database. If you are using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, ‘os.path.join(BASE_DIR, ‘db.sqlite3’)’, will store the file in your project directory

  1. Note the INSTALLED_APPS setting at the top of the file. That holds the names of all Django applications that are activated in this Django instance.
  2. By default, INSTALLED_APPS contains the following apps, all of which come with Django:

18.1            django.contrib.admin – the admin site

18.2            django.contrib.auth – An authentication system

18.3            django.contrib.contenttype – a framework for content types

18.4            django.contrib.sessions – a session framework

18.5            django.contrib.messages – a messaging framework

18.6            django.contrib.staticfiles – a framework for managing static files

  1. some of these applications makes use of at least one database table, though. So we need to create the tables in the database before we can use them. To do that, run the following command: python manage.py syncdb
  2. the syncdb command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file. You’ll see a message for each database table it creates
  3. the default applications are included for the common case, but not everybody needs them. If you don’t need any or all of them. Feel free to comment-out or delete the appropriate line(s) from INSTALLED_APPS before running syncdb. The syncdb command will only create tables for apps in INSTALLED_APP
  4. what’s the difference between a project and an app? An App is a web application that does something – e.g. a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
  5. Your apps can live anywhere on your Python path.
  6. To create your app, make sure you are in the same directory as manage.py and type this command: python manage.py startapp polls
  7. The first step in writing a database web application in Django is to define your models – essentially, your database layout, with additional metadata
  8. A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY principle. The goal is to define your data model in one place and automatically derive things from it.
  9. Each model is represented by a class that subclass Django.db.models.Model. each model has a number of class variables, each of which represents a database field in the model.
  10. Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.
  11. The name of each Field instance is the field’s name, in machine-friendly format. You’ll use this value in your Pytohn code, and your database will use it as the column name.
  12. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
  13. Django apps are “plugable”: you can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation
  14. And your app to INSTALLED_APPS and run “python mange.py sql your_app”
  15. Python manage.py validate – Checks for any errors in the construction of your models
  16. Python manage.py sqlcustom polls – Outputs any custom SQL statement (such as table modifications or constraints) that are defined for the application.
  17. Python mange.py sqlclear polls – Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any)
  18. Python manage.py sqlindexes polls – Output the CREATE INDEX statements for this app.
  19. Python manage.py sqlall polls – a combination of all the SQL from the sql, sqlcustom and sqlindexes commands
  20. Run syncdb again to create those model tables in your database: python manage.py syncdb
  21. Syncdb can be called as often as you can, and it will only ever create the tables that don't exist.
  22. To invoke the Python shell, use this command: python manage.py shell
  23. We are using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTING_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file
  24. It’s important to add __unicode__ methods (or __str__() on Python 3) to your modules, not only for your own sanity when dealing with the interactive prompt, but also because object’s representations are used to throughout Django’s automatically generated admin.
  25. We use __unicode__ because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it’s returned.
  26. Django models have a default __str__() method that calls __unicode__() and converts the result to a UTF-8 bytestring. This means that Unicode(p) will return a Unicode string, and str(p) will return a normal string, with character encoded as UTF-8.
  27. Creating superusers: python manage.py createsuperuser –username=joe –email=joe@example.com
  28. Visit admin site: http://localhost:8000/admin
  29. Make the poll app modifiable in the admin:  we need to tell the admin that Poll objects have an admin interface. (edit polls/admin.py)
  30. The different model field types(DateTimeField, CharField) correspond to the appropriate HTML input widget. Each type of field knows how to display itself in the Django admin.
  31. Create a model admin object, then pass ot as the second argument to admin.site.register() – any time you need to change the admin options for an object.
  32. You can assign arbitrary HTML classes to each fieldset. Django provides a “collapse” class that displays a particular fieldset initially collapsed.
  33. Django knows that a ForeignKey should be represented in the admin as a <select> box.
  34. By default, Django displays the str() of each object.
  35. Use the list_display admin option, which is a tuple of field names to display, as columns, on the change list page for the object.
  36. You can click on the column headers to sort by those values – except in the case of the was_published_recently header, because sorting by the output of an arbitrary methods is not supported.
  37. Create a templates directory in your project directory. Template can live anywhere on your filesystem that Django can access.
  38. Open you settings file (mysite/settings.py), and add a TEMPLATE_DIRS setting:

TEMPLATE_DIR = [os.path.join(BASE_DIR, 'templates')]

TEMPLATE_DIR is an iterable of filesystem directories to check when loading Django templates; it’s a search path.

  1. But if TEMPLATE_DIRS was empty by default, how was Django finding the default admin templates? The answer is that, by default, Django automatically looks for a templates/subdirectory within each application package, for use as a fallback.
  2. By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order.
  3. Edit admin/index.html, app_list, the variable contains every installed Django app.
  4. A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template.
  5. In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views). Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name).
  6. A URL pattern is simply the general form of a URL.
  7. To get from a URL to a view, Django uses what we are known as “URLconfs”. A URLconf maps URL patterns (described as regular expressions) to views.
  8. To call the view, we need to map it to a URL – and for this, we need a URLconf.
  9. The url() function is passed 4 arguments, two required: regex and view, and two optional: kwargs, and name.
  10. url() argument: regex: Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.
  11. url() argument: view: when Django finds a regular expression match, Django calls the specified view function, with an HttpRequest object as the first argument and any “captured” values from the regular expression as other arguments. If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments.
  12. url() argument: name: Naming your URL lets you refer to it unambiguously from elsewhere in Django especially templates.
  13. When somebody requests a page from your web site, Django will load the mysite.urls Python module because it’s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the regular expressions in order. The include() functions we are using simply reference other URLconfs.
  14. Each view is responsible for doing one of two things: returning an HtppResponse object containing the content for the requested page, or raising an exception such as Http404
  15. All Django wants is that HttpResponse. Or an exception.
  16. Django’s TEMPLATE_LOADERS setting contains a list of callables that know how to import templates from various sources. One of the defaults is Django.template.loaders.app_directories.Loader which looks for a “template” subdirectory in each of the INSTALLED_APPS
  17. The render() function takes the request object as its first argument, a template name as its second argument and a directory as its optional argument. It returns an HttpResponse object of the given template rendered with the given context.
  18. The get_object_or_404 function takes a Django model as its first argument and an arbitrary number of keyword arguments, which it passes to the get() function of the models’s manager. It raises Http404 if the object doesn't exist.
  19. There is also a get_list_or_404() function, which works just as get_object_or_404() – except using filter() instead of get(). It raises Http404 if the list is empty.
  20. The template system uses dot-lookup syntax to access variable attributes.
  21. Namespacing URL names: the answer is to add namespaces to your root URLconf. In the mysite/urls.py (the project’s urls.py, not the application’s)
  22. Request.POST is a dictionary-like object that lets you access submitted data by key name. a string request.POST values are always string. Note that Django also provides request.GE for accessing GET data in the same way
  23. Reverse() function in the HttpResponseRedirect helps avoid having to hardcode a URL in the view function. It is given name of the view that we want to pass control to and the variable portion of the URL pattern that points to that view.
  24. ListView and DetaiView. Respectively, those two views abstract the concepts of “display a list of objects” and “display a detail page for a particular type of object”
  25. Each generic view needs to know what model it will be acting upon. This is provided using the model attribute.
  26. The DetailView generic view expects the primary key value captured from the URL to be called “pk”, so we’ve changed poll_id to pk for the generic views.
  27. By default, the DetailView generic view uses a template called <app name>/<model name>_detail.html
  28. A conventional place for an application’s tests in the application’s tests.py file; the testing system will automatically find tests in any file whose name begins with test.
  29. Running tests: python manage.py test polls
  30. Django provides a test Client to simulate a user interacting with the code at the view level. We can use it in tests.py or even in the shell.
  31. Django will look for static files in static folder
  32. Django’s STATICFILES_FIN?DERS setting contains a list of finders that know how to discover static files from various source. One of the defaults is AppDirectoriesFinder which looks for a “static” subdirectory in each of the INSTALLED_APPS.

Writing your first Django的更多相关文章

  1. Writing your first Django app, part 1(转)

    Let’s learn by example. Throughout this tutorial, we’ll walk you through the creation of a basic pol ...

  2. # Writing your first Django app--part 3 about view

    添加更多的view 写actually有用的view 使用模版来设计view 使用模版设计view的捷径:render() 抛出异常404 抛出异常404-快捷方法: get_object_or_40 ...

  3. # Writing your first Django app, part 2

    创建admin用户 D:\desktop\todoList\Django\mDjango\demoSite>python manage.py createsuperuser 然后输入密码 进入a ...

  4. Django 静态文件配置(static files)

    Django version: 1.9 Python versrion: 3.5.2 这几天Django配置静态文件(本例是要加载index.css), 总是不对,最后终于试对了,这里记录下,方便以后 ...

  5. Django入门教程(二)

    建议直接阅读末尾!!! Writing your first Django app, part 2 本节将设置数据库,创建您的第一个模型(model),并简单介绍Django自动生成的管理页面. 数据 ...

  6. win7下,使用django运行django-admin.py无法创建网站

    安装django的步骤: 1.安装python,选择默认安装在c盘即可.设置环境变量path,值添加python的安装路径. 2.下载ez_setup.py,下载地址:http://peak.tele ...

  7. Django 2.0.1 官方文档翻译: 文档目录 (Page 1)

    Django documentation contents 翻译完成后会做标记. 文档按照官方提供的内容一页一页的进行翻译,有些内容涉及到其他节的内容,会慢慢补上.所有的翻译内容按自己的理解来写,尽量 ...

  8. Django文档阅读-Day2

    Django文档阅读 - Day2 Writing your first Django app, part 1 You can tell Django is installed and which v ...

  9. Django文档阅读-Day3

    Django文档阅读-Day3 Writing your first Django app, part 3 Overview A view is a "type" of Web p ...

随机推荐

  1. Oracle 12C -- in-database archiving

    在同一张表中,通过将row置为inactive状态来实现数据的归档.数据库中,可以对那些inactive row进行压缩优化.在实现归档的同时,应用可以被限制只访问那些active状态的数据.默认情况 ...

  2. Selenium2自动化测试实战序言

    记得很久之前接触自动化的时候看了一本关于某早期自动化测试工具的书,书名已经记不得了,内容却一直印象深刻.因为那本书根本就是把官方文档有选择性的翻译一遍,对于实际应用来说其作用几乎是零.因此从那时候起我 ...

  3. 关于try catch

    说明try块中有return语句时,仍然会首先执行finally块中的语句,然后方法再返回. 如果try块中存在System.exit(0);语句,那么就不会执行finally块中的代码,因为Syst ...

  4. Oracle数据库中number类型在java中的使用

    1)如果不指定number的长度,或指定长度n>18 id number not null,转换为pojo类时,为java.math.BigDecimal类型 2)如果number的长度在10 ...

  5. springboot 多模块 maven 项目构建jar 文件配置

    最近在写 springboot 项目时,需要使用多模块,遇到了许多问题. 1 如果程序使用了 java8 的一些特性,springboot 默认构建工具不支持.需要修改配置 ... </buil ...

  6. FFT节省资源的思路

    作者:桂. 时间:2017-01-18  23:07:50 链接:http://www.cnblogs.com/xingshansi/articles/6298391.html 前言 FFT是信号处理 ...

  7. [转载]java日志框架log4j详细配置及与slf4j联合使用教程

    一.log4j基本用法 首先,配置log4j的jar,maven工程配置以下依赖,非maven工程从maven仓库下载jar添加到“build path” 1 2 3 4 5 <dependen ...

  8. UVa 10697 - Firemen barracks

    题目:已知三点.求到三点距离同样的点. 分析:计算几何.分三类情况讨论: 1.三点共线,不成立. 2.多点重叠,有多组解. 3.是三角形,输出中点. 说明:注意绝对值小于0.05的按0计算:负数的四舍 ...

  9. hdu 2680 Choose the best route (dijkstra算法)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2680 /************************************************* ...

  10. CCardSlip

    该类已经把tableview封装好,可以把它当做一个精灵来用,这样做的好处是,当一个界面同时需要多个tableview的时候就可以很好的解决这个问题,而且模块也更清晰. //------------- ...