Chúng ta hay cùng học qua các ví dụ.
Trong các bài hướng dẫn, chúng sẽ cùng tạo một ứng dụng thăm dò ý kiến
Nó sẽ bao gồm hai phần
Ví dụ:
Nếu Django đã được cài đặt bạn sẽ thấy phiên bản là cài đặt. Nếu nó
chưa được cài đặt bạn sẽ thấy thông báo “No module named django”
Hướng dẫn này dành cho Django 1.5.5 và Python 2.x. Nếu phiên bản không đúng, bạn có thể xem thêm hướng dẫn dành cho phiến bản Django của bạn hoặc cập nhật phiên bản Django mới nhất. Nếu bạn đang sử dụng Python 3.x, bạn nên chú ý code của bạn có thể khác với bài hướng dẫn này và bạn chỉ tiếp tục sử dụng hướng dẫn nếu bạn biết rõ bạn đang làm gì với Python 3.x.
Xem How to install Django để bạn có thể remote hoặc nâng cấp phiên bản Django mới hơn.
Câu lệnh này sẽ tạo thư mục mysite trong thư mục hiện tại của bạn. Nếu nó không hoạt động, bạn xem thêm tại Problems running django-admin.py.
Bây giờ là thời điểm để lưu ý: Không sử dụng máy chủ này trong bất cứ điều gì như môi trường chạy thật. Nó chỉ sử dụng trong khi phát triển. (Chúng ta đang trong việc kinh doanh của việc phát triển Web không phải máy chủ web.)
Bây giờ máy chủ đang chạy, vào trang http://127.0.0.1:8000/ với trình duyệt của bạn. Bạn sẽ thấy một trang thông báo “Welcome to Django”. Điều đó chứng tỏ nó đã làm việc.
Now, edit mysite/settings.py. Nó là một mô đun bình thường với các cấp mô đun đại diện cho cài đặt Django. Thay đổi các từ khóa trong phần DATABASES 'default' những mục của thiết lập cơ sở dữ liệu.
Tuyên nhiên hãy ghi nhớ INSTALLED_APPS được đặt ở dưới cùng. Tên ứng dụng mà Django hoạt động trong một instance. ứng dụng có thể sử dụng ở nhiều dự án, bạn có thể đóng gói và sử dụng chúng cho dự án khác.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
Each 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:
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, and you’ll get
a prompt asking you if you’d like to create a superuser account for the
authentication system. Go ahead and do that.
If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), or.schema (SQLite) to display the tables Django created.
Each application you write in Django consists of a Python package, somewhere on your Python path, that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
To create your app, make sure you’re in the same directory as manage.py and type this command:
That’ll create a directory polls, which is laid out like this:
This directory structure will house the poll application.
The first step in writing a database Web app in Django is to define your models – essentially, your database layout, with additional metadata.
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:
The code is straightforward. Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.
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.
The name of each Field instance (e.g. question or pub_date ) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.
You can use an optional first positional argument to a Field to designate a human-readable name. That’s used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn’t provided, Django will use the machine-readable name. In this example, we’ve only defined a human-readable name for Poll.pub_date. For all other fields in this model, the field’s machine-readable name will suffice as its human-readable name.
Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.
A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.
Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
Now Django knows to include the polls app. Let’s run another command:
You should see something similar to the following (the CREATE TABLE SQL statements for the polls app):
Note the following:
Now, run syncdb again to create those model tables in your database:
The syncdb command runs the SQL from sqlall on your database for all apps in INSTALLED_APPS that
don’t already exist in your database. This creates all the tables,
initial data and indexes for any apps you’ve added to your project since
the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don’t exist.
Read the django-admin.py documentation for full information on what the manage.py utility can do.
Bạn có thể dùng câu lệnh để thực hiện các tác vụ mà Django cung cấp/
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.
Wait a minute. <Poll: Poll object> is, utterly, an unhelpful representation of this object. Let’s fix that by editing the polls model (in the polls/models.py file) and adding a __unicode__() method to both Poll and Choice. On Python 3, simply replace__unicode__ by __str__ in the following example:
It’s important to add __unicode__() methods (or __str__() on
Python 3) to your models, not only for your own sanity when dealing
with the interactive prompt, but also because objects’ representations
are used throughout Django’s automatically-generated admin.
Note the addition of import datetime and from django.utils import timezone, to reference Python’s standard datetimemodule and Django’s time-zone-related utilities in django.utils.timezone, respectively. If you aren’t familiar with time zone handling in Python, you can learn more in the time zone support docs.
Save these changes and start a new Python interactive shell by running python manage.py shell again:
For more information on model relations, see Accessing related objects. For more on how to use double underscores to perform field lookups via the API, see Field lookups. For full details on the database API, see our Database API reference.
When you’re comfortable with the API, read part 2 of this tutorial to get Django’s automatic admin working.
Trong các bài hướng dẫn, chúng sẽ cùng tạo một ứng dụng thăm dò ý kiến
Nó sẽ bao gồm hai phần
- Trang public cho người dùng, người dùng có thể bình chọn.
- Quản trị viên có thể thay đổi, thêm mới, hoặc xóa thăm dò ý kiến.
Ví dụ:
python -c "import django; print(django.get_version())"
Hướng dẫn này dành cho Django 1.5.5 và Python 2.x. Nếu phiên bản không đúng, bạn có thể xem thêm hướng dẫn dành cho phiến bản Django của bạn hoặc cập nhật phiên bản Django mới nhất. Nếu bạn đang sử dụng Python 3.x, bạn nên chú ý code của bạn có thể khác với bài hướng dẫn này và bạn chỉ tiếp tục sử dụng hướng dẫn nếu bạn biết rõ bạn đang làm gì với Python 3.x.
Xem How to install Django để bạn có thể remote hoặc nâng cấp phiên bản Django mới hơn.
Bạn cần giúp đỡ:
Nếu bạn có vấn đề với hướng dẫn này, hãy đưa vấn đề đó lên django-users hoặc thảo luận trên #django on irc.freenode.net với mọi người, họ có thể giúp bạn.
Nếu bạn có vấn đề với hướng dẫn này, hãy đưa vấn đề đó lên django-users hoặc thảo luận trên #django on irc.freenode.net với mọi người, họ có thể giúp bạn.
Tạo một dự án mới
Nếu bạn là người sử dụng Django lần đầu, bạn sẽ phải thành tạo các
bước cài đặt. Cụ thể, bạn sẽ cần sinh mã nguồn thiết lập môi trường
Django – tổng hợp các cài đặt cho một phiên làm việc của Django, bao gồm
cấu hình cơ sở dữ liệu, các tùy chọn đặc biệt, và các thiết lập cho ứng
dụng cụ thể.
Từ dòng lệnh, cd đến thư mục mà bạn muốn lưu trữ mã nguồn của bạn, sau đó bạn chạy lệnh sau:
django-admin.py startproject mysite
Ghi nhớ
Bạn sẽ cần phải tránh đặt tên các dự án sau khi được xây dựng trong các thành phần Python hay Django. Cụ thể, điều này có nghĩa là bạn nên tránh sử dụng những cái tên như django (mà sẽ xung đột với Django) hoặc test (có xung đột với một thành phần của Python).
Bạn sẽ cần phải tránh đặt tên các dự án sau khi được xây dựng trong các thành phần Python hay Django. Cụ thể, điều này có nghĩa là bạn nên tránh sử dụng những cái tên như django (mà sẽ xung đột với Django) hoặc test (có xung đột với một thành phần của Python).
Mã nguồn bạn nên đặt ở đâu?
Nếu môi trường của bạn đã có PHP (nó không sử dụng các mô hình hiện tại), bạn sẽ đặt mã nguồn của bạn vào thư mục gốc của máy chủ web (ví dụ như: /var/ww/).
Với Django, bạn không làm điều đó. Nó không là một ý tưởng tốt để đưa toàn bộ mã nguồn lên thư mục gốc của máy chủ web, bởi vì nguy cơ bạn bị lộ mã nguồn trên trang web. Nó thực sự không tốt cho bảo mật.
Đặt mã nguồn của bạn lên một thư mục khác ngoài thư mục gốc, ví dụ /home/mycode.
Bạn thử xem những gì được tạo bởi startproject:Nếu môi trường của bạn đã có PHP (nó không sử dụng các mô hình hiện tại), bạn sẽ đặt mã nguồn của bạn vào thư mục gốc của máy chủ web (ví dụ như: /var/ww/).
Với Django, bạn không làm điều đó. Nó không là một ý tưởng tốt để đưa toàn bộ mã nguồn lên thư mục gốc của máy chủ web, bởi vì nguy cơ bạn bị lộ mã nguồn trên trang web. Nó thực sự không tốt cho bảo mật.
Đặt mã nguồn của bạn lên một thư mục khác ngoài thư mục gốc, ví dụ /home/mycode.
mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py
Nếu bạn không thấy nó hiện thị đúng?
Phần mặc định đã được thay đổi. Nếu bạn đang nhìn thấy không có sự bố trí thư mục (không có thư mục mysite/ ), bạn có thể đang sử dụng phiên bản Django khác với hướng dẫn này. Bạn cần chuyển sang hướng dẫn khác hoặc phiên bản Django mới hơn.
Có các tập tin sau:Phần mặc định đã được thay đổi. Nếu bạn đang nhìn thấy không có sự bố trí thư mục (không có thư mục mysite/ ), bạn có thể đang sử dụng phiên bản Django khác với hướng dẫn này. Bạn cần chuyển sang hướng dẫn khác hoặc phiên bản Django mới hơn.
- Thư mục mysite/ ngoài cùng là thư mục chưa dự án của bạn. Tên của nó không thể là Django; bạn có thể thay đổi tên nó tùy ý.
- manage.py: Một câu lệnh giúp bạn làm việc với dự án Django với nhiều cách khác nhau. Bạn có thể đọc chi tiết về manage.py trong django-admin.py and manage.py.
- Thư mục mysite/ trong bao gồm các gói Python thực tế của dự án. Tên của các gói Python bạn sẽ sử dụng trong việc import bất cứ những gì trong nó (ví dụ: mysite.urls).
- mysite/__init__.py: Một tập tin trống cho Python biết rằng đó thư mục bao gồm các gói của Python. (Đọc thêm more about packages trong tài liệu Python cho người đắt đầu).
- mysite/settings.py: Thiết lập/ Cấu hình cho Django. Django settings sẽ bao gồm các thông số cho việc cài đặt chung.
- mysite/urls.py: Các URL của dự án Django; nó là như là một mục lục của dự án Django. Bạn có thể đọc thêm về URLs tại URL dispatcher.
- mysite/wsgi.py: Một chỉ mục cho máy chủ web tương thích với WSGI để phục vụ dự án có thể chạy. Xem thêm tại How to deploy with WSGI.
Máy chủ phát triển
Bạn hãy kiểm tra lại sự hoạt động của máy chủ. Chuyển đến thư mục mysite, nếu hệ thống sẵn sàng và chạy lệnh sau:
python manage.py runserver
Bạn sẽ thấy xuất hiện dòng thông báo như hình dưới đây:Validating models... 0 errors found October 31, 2013 - 15:50:53 Django version 1.5.5, using settings 'mysite.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.Bạn khởi động máy chủ phát triển Django, một máy chủ được viết hoàn toàn bằng Python. Chúng ta đã có Django và bạn cũng có thể phát triển một cách nhanh chóng, mà không cần quan tâm đến cấu hình của máy chủ như Apache đến khi bạn có hệ thống chạy thật.
Bây giờ là thời điểm để lưu ý: Không sử dụng máy chủ này trong bất cứ điều gì như môi trường chạy thật. Nó chỉ sử dụng trong khi phát triển. (Chúng ta đang trong việc kinh doanh của việc phát triển Web không phải máy chủ web.)
Bây giờ máy chủ đang chạy, vào trang http://127.0.0.1:8000/ với trình duyệt của bạn. Bạn sẽ thấy một trang thông báo “Welcome to Django”. Điều đó chứng tỏ nó đã làm việc.
Đổi cổng
Mặc định, câu lệnh runserver sẽ khởi động máy chủ phát triển với IP và cổng trong nội bộ 8000
Nếu bạn muốn đổi cổng máy chủ, vượt qua nó bằng một số dòng lệnh. Trong phần này, câu lệnh sẽ khởi động máy chủ cổng 8080
Nếu bạn muốn thay đổi địa chỉ IP, truy cập với cổng. Và nó cũng sẽ
công khai với toàn bộ IP (có tác dụng nếu bạn sử dụng máy tính khác để
làm việc) bạn sử dụng câu lệnh:
Toàn bộ tài liệu phát triển máy chủ bạn có thể tìm thấy phần runserver.
Mặc định, câu lệnh runserver sẽ khởi động máy chủ phát triển với IP và cổng trong nội bộ 8000
Nếu bạn muốn đổi cổng máy chủ, vượt qua nó bằng một số dòng lệnh. Trong phần này, câu lệnh sẽ khởi động máy chủ cổng 8080
python manage.py runserver 8080
python manage.py runserver 0.0.0.0:8000
Tự động tải lại của runserver
Máy chủ phát triển sẽ tự động tải lại mã nguồn Python cho mỗi yêu cầu khi cần thiết. Bạn không cần khởi động lại máy chủ để thay đổi mã nguồn. Tuy nhiên một số hành động như biên dịch tập tin hoặc thêm dòng không kích hoạt khởi động lại máy chủ, chính vì vậy trong trường hợp này bạn cần khởi động lại máy chủ.
Máy chủ phát triển sẽ tự động tải lại mã nguồn Python cho mỗi yêu cầu khi cần thiết. Bạn không cần khởi động lại máy chủ để thay đổi mã nguồn. Tuy nhiên một số hành động như biên dịch tập tin hoặc thêm dòng không kích hoạt khởi động lại máy chủ, chính vì vậy trong trường hợp này bạn cần khởi động lại máy chủ.
Cài đặt máy chủ dữ liệu
Tiếp theo, chỉnh sửa mysite/settings.py.Now, edit mysite/settings.py. Nó là một mô đun bình thường với các cấp mô đun đại diện cho cài đặt Django. Thay đổi các từ khóa trong phần DATABASES 'default' những mục của thiết lập cơ sở dữ liệu.
- ENGINE – Mỗi thiết lập'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql','django.db.backends.sqlite3' or 'django.db.backends.oracle'. Cho mỗi kết nối also available.
- NAME –
Tên của cơ sở dữ liệu. Nếu bạn sử dụng SQLite, cơ sở dữ liệu sẽ là một
tập tin trong máy của bạn; trong lựa chọn này, NAME sẽ bao gồm đường
dẫn chuẩn, bao gồm tên tập tin. Nếu tập tin đã có, nó sẽ tự động tạo khi
bạn tự đồng bộ cơ sở dữ liệu cho lần đầu tiên (như phía dưới)
(Khi xác định đường dẫn, bạn luôn dùng dấu / kể cả với Windows.)
(e.g. C:/homes/user/mysite/sqlite3.db).
USER – Tài khoản của cơ sở dữ liệu (không có tác dụng với SQLite). - PASSWORD – Mật khẩu cơ sở dữ liệu (không sử dụng với SQLite).
- HOST – Máy chủ cơ sở dữ liệu hoạt động. Để nguyên nếu như không có (hoặc điền 127.0.0.1) Máy chủ cơ sở dữ liệu được thiết lập, nếu máy chủ cơ sở dữ liệu trên máy vật lý (Không dùng SQLite). Bạn có thể tìm hiểu thêm tại HOST.
Ghi nhớ
Nếu bạn sử dựng PostgreSQL hoặc MySQL, hãy chắc chắn rằng cơ sở dữ liệu của bạn được tạo đúng.
Nếu bạn sử dụng SQLite, bạn không cần tạo bất cứ thứ gì trước đó – tập tin cơ sở dữ liệu sẽ được tạo tự động khi nó cần.
Khi bạn chỉnh sửa tập tin settings.py, thiết lập TIME_ZONE vùng bạn đang sinh sống. Mặc định sẽ là U.S. (Chicago).Nếu bạn sử dựng PostgreSQL hoặc MySQL, hãy chắc chắn rằng cơ sở dữ liệu của bạn được tạo đúng.
Nếu bạn sử dụng SQLite, bạn không cần tạo bất cứ thứ gì trước đó – tập tin cơ sở dữ liệu sẽ được tạo tự động khi nó cần.
Tuyên nhiên hãy ghi nhớ INSTALLED_APPS được đặt ở dưới cùng. Tên ứng dụng mà Django hoạt động trong một instance. ứng dụng có thể sử dụng ở nhiều dự án, bạn có thể đóng gói và sử dụng chúng cho dự án khác.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
- django.contrib.auth – An authentication system.
- django.contrib.contenttypes – A framework for content types.
- django.contrib.sessions – A session framework.
- django.contrib.sites – A framework for managing multiple sites with one Django installation.
- django.contrib.messages – A messaging framework.
- django.contrib.staticfiles – A framework for managing static files.
Each 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
If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), or.schema (SQLite) to display the tables Django created.
For the minimalists
Like we said above, 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_APPSbefore running syncdb. The syncdb command will only create tables for apps in INSTALLED_APPS.
Like we said above, 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_APPSbefore running syncdb. The syncdb command will only create tables for apps in INSTALLED_APPS.
Creating models
Now that your environment – a “project” – is set up, you’re set to start doing work.Each application you write in Django consists of a Python package, somewhere on your Python path, that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.
Projects vs. apps
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.
Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.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.
To create your app, make sure you’re in the same directory as manage.py and type this command:
python manage.py startapp polls
polls/ __init__.py models.py tests.py views.py
The first step in writing a database Web app in Django is to define your models – essentially, your database layout, with additional metadata.
Philosophy
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.
In our simple poll app, we’ll create two models: Poll and Choice. A Poll has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Poll.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.
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
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.
The name of each Field instance (e.g. question or pub_date ) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.
You can use an optional first positional argument to a Field to designate a human-readable name. That’s used in a couple of introspective parts of Django, and it doubles as documentation. If this field isn’t provided, Django will use the machine-readable name. In this example, we’ve only defined a human-readable name for Poll.pub_date. For all other fields in this model, the field’s machine-readable name will suffice as its human-readable name.
Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.
A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.
Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.
Activating models
That small bit of model code gives Django a lot of information. With it, Django is able to:- Create a database schema (CREATE TABLE statements) for this app.
- Create a Python database-access API for accessing Poll and Choice objects.
Philosophy
Django apps are “pluggable”: 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.
Edit the settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls'. So it’ll look like this:Django apps are “pluggable”: 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.
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', )
python manage.py sql polls
BEGIN; CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ); COMMIT;
- The exact output will vary depending on the database you are using.
- Table names are automatically generated by combining the name of the app (polls) and the lowercase name of the model – poll and choice. (You can override this behavior.)
- Primary keys (IDs) are added automatically. (You can override this, too.)
- By convention, Django appends "_id" to the foreign key field name. (Yes, you can override this, as well.)
- The foreign key relationship is made explicit by a REFERENCES statement.
- It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial(PostgreSQL), or integer primary key (SQLite) are handled for you automatically. Same goes for quoting of field names – e.g., using double quotes or single quotes. The author of this tutorial runs PostgreSQL, so the example output is in PostgreSQL syntax.
- The sql command doesn’t actually run the SQL in your database – it just prints it to the screen so that you can see what SQL Django thinks is required. If you wanted to, you could copy and paste this SQL into your database prompt. However, as we will see shortly, Django provides an easier way of committing the SQL to the database.
- python manage.py validate – Checks for any errors in the construction of your models.
- python manage.py sqlcustom polls – Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
- python manage.py sqlclear polls – Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
- python manage.py sqlindexes polls – Outputs the CREATE INDEX statements for this app.
- python manage.py sqlall polls – A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.
Now, run syncdb again to create those model tables in your database:
python manage.py syncdb
Read the django-admin.py documentation for full information on what the manage.py utility can do.
Playing with the API
Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:Bạn có thể dùng câu lệnh để thực hiện các tác vụ mà Django cung cấp/
python manage.py shell
Bypassing manage.py
If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable tomysite.settings and run python from the same directory manage.py is in (or ensure that directory is on the Python path, so that import mysite works).
For more information on all of this, see the django-admin.py documentation.
Once you’re in the shell, explore the database API:If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable tomysite.settings and run python from the same directory manage.py is in (or ensure that directory is on the Python path, so that import mysite works).
For more information on all of this, see the django-admin.py documentation.
>>> from polls.models import Poll, Choice # Import the model classes we just wrote. # No polls are in the system yet. >>> Poll.objects.all() [] # Create a new Poll. # Support for time zones is enabled in the default settings file, so # Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. >>> from django.utils import timezone >>> p = Poll(question="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. >>> p.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. >>> p.id 1 # Access database columns via Python attributes. >>> p.question "What's new?" >>> p.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # Change values by changing the attributes, then calling save(). >>> p.question = "What's up?" >>> p.save() # objects.all() displays all the polls in the database. >>> Poll.objects.all() [<Poll: Poll object>]
class Poll(models.Model): # ... def __unicode__(self): # Python 3: def __str__(self): return self.question class Choice(models.Model): # ... def __unicode__(self): # Python 3: def __str__(self): return self.choice_text
__unicode__() or __str__()?
On Python 3, things are simpler, just use __str__() and forget about __unicode__().
If you’re familiar with Python 2, you might be in the habit of adding __str__() methods to your classes, not__unicode__() methods. We use __unicode__() here because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it’s returned.
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 characters encoded as UTF-8.
If all of this is gibberish to you, just remember to add __unicode__() methods to your models. With any luck, things should Just Work for you.
Note these are normal Python methods. Let’s add a custom method, just for demonstration:On Python 3, things are simpler, just use __str__() and forget about __unicode__().
If you’re familiar with Python 2, you might be in the habit of adding __str__() methods to your classes, not__unicode__() methods. We use __unicode__() here because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it’s returned.
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 characters encoded as UTF-8.
If all of this is gibberish to you, just remember to add __unicode__() methods to your models. With any luck, things should Just Work for you.
import datetime from django.utils import timezone # ... class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Save these changes and start a new Python interactive shell by running python manage.py shell again:
>>> from polls.models import Poll, Choice # Make sure our __unicode__() addition worked. >>> Poll.objects.all() [<Poll: What's up?>] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(id=1) [<Poll: What's up?>] >>> Poll.objects.filter(question__startswith='What') [<Poll: What's up?>] # Get the poll that was published this year. >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Poll.objects.get(pub_date__year=current_year) <Poll: What's up?> # Request an ID that doesn't exist, this will raise an exception. >>> Poll.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Poll matching query does not exist. Lookup parameters were {'id': 2} # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. # The following is identical to Poll.objects.get(id=1). >>> Poll.objects.get(pk=1) <Poll: What's up?> # Make sure our custom method worked. >>> p = Poll.objects.get(pk=1) >>> p.was_published_recently() True # Give the Poll a couple of Choices. The create call constructs a new # Choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. Django creates # a set to hold the "other side" of a ForeignKey relation # (e.g. a poll's choices) which can be accessed via the API. >>> p = Poll.objects.get(pk=1) # Display any choices from the related object set -- none so far. >>> p.choice_set.all() [] # Create three choices. >>> p.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> p.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> c = p.choice_set.create(choice_text='Just hacking again', votes=0) # Choice objects have API access to their related Poll objects. >>> c.poll <Poll: What's up?> # And vice versa: Poll objects get access to Choice objects. >>> p.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> p.choice_set.count() 3 # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. # Find all Choices for any poll whose pub_date is in this year # (reusing the 'current_year' variable we created above). >>> Choice.objects.filter(poll__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # Let's delete one of the choices. Use delete() for that. >>> c = p.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()
When you’re comfortable with the API, read part 2 of this tutorial to get Django’s automatic admin working.
Tags:
Python Framework