码迷,mamicode.com
首页 > 其他好文 > 详细

Writing your first Django

时间:2014-04-30 23:14:34      阅读:566      评论:0      收藏:0      [点我收藏+]

标签:des   com   http   blog   class   code   c   log   t   tar   sp   

  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,码迷,mamicode.com

Writing your first Django

标签:des   com   http   blog   class   code   c   log   t   tar   sp   

原文地址:http://www.cnblogs.com/bluescorpio/p/3701320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!