Python Django的使用:Writing your first Django app--实践

来源:互联网 发布:windows vista精简版 编辑:程序博客网 时间:2024/06/07 11:12

Writing your first Django app, part 1

安装django

C:\Windows\system32>python -m django --version

1.10.2

Creating a project

From the command line, cd into a directory where you’d like to store your code, then run the following command:

D:\>cd D:\code-github

D:\code-github>django-admin startproject mysite

创建之后的目录结构为:

D:\code-github\mysite>tree /f

D:.

│  db.sqlite3

│  manage.py

├─mysite

│  │  settings.py

│  │  urls.py

│  │  wsgi.py

│  │  __init__.py

│  │

│  └─__pycache__

│          settings.cpython-35.pyc

│          urls.cpython-35.pyc

│          wsgi.cpython-35.pyc

│          __init__.cpython-35.pyc

The outer mysite/ root directory is just a container for your project

manage.py: A command-line utility that lets you interact with this Django project in various ways

The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name youll need to use to import anything inside it (e.g. mysite.urls)

mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package.

mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.

mysite/urls.py: The URL declarations for this Django project; a table of contentsof your Django-powered site;

mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project

The development server

Lets verify your Django project works. Change into the outer mysite directory, if you havent already, and run the following commands:$ python manage.py runserver

Youve started the Django development server, a lightweight Web server written purely in Python. Weve included this with Django so you can develop things rapidly, without having to deal with configuring a production serversuch as Apacheuntil youre ready for production

已经启动django server,集成了一个轻量级、纯pythonweb server容器;可以快速用于开发

执行python manage.py runserver之后:

October 27, 2016 - 13:55:03 Django version 1.10.2, using settings 'mysite.settings'Starting development server athttp://127.0.0.1:8000/  Quit the server with CTRL-BREAK.

If you want to change the servers port, pass it as a command-line argument. For instance, this command starts the server on port 8080:$python manage.py runserver 8080

Creating the Polls app

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.

Your apps can live anywhere on your Python path. In this tutorial, well 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

To create your app, make sure youre in the same directory as manage.py and type this command:

$ python manage.py startapp polls

D:\code-github\mysite>tree /f polls

D:\CODE-GITHUB\MYSITE\POLLS

│  admin.py

│  apps.py

│  models.py

│  tests.py

│  views.py

│  __init__.py

└─migrations

        __init__.py

Write your first view

Lets write the first view. Open the filepolls/views.py and put the following Python code in it

from django.shortcutsimportrender;
# Create your views here.
from django.httpimportHttpResponse;
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.");

 

To call the view, we need to map it to a URL - and for this we need a URLconf.To create a URLconf in the polls directory, create a file called urls.py. In the polls/urls.py file include the following code:

from django.conf.urlsimporturl
from . importviews
urlpatterns = [
    url(r'^$', views.index,name='index'),
]

The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import for django.conf.urls.include and insert an include() in the urlpatterns list, so you have:mysite/urls.py

"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))

"""
from django.conf.urlsimportinclude, url
from django.contrib import admin


urlpatterns = [
    
url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

测试网页

[1]http://127.0.0.1:8000/

Page not found (404)

Request Method: GET

Request URL: http://127.0.0.1:8000/

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

^polls/

^admin/

The current URL, , didn't match any of these.

 

[2]http://127.0.0.1:8000/polls/

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

 

[3]http://127.0.0.1:8000/admin/login/

 

关于admin用户的配置python manage.py createsuperuse,后续讲述。

Writing your first Django app, part 2

his tutorial begins where Tutorial 1 left off. Well setup the database, create your first model, and get a quick introduction to Djangos automatically-generated admin site.

Database setup

By default, the configuration uses SQLite.SQLite is included in Python.mysite/settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR,'db.sqlite3'),
    }
}

 

[1]ENGINE: Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle

[2]NAME The name of your database. If youre 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.

[3]If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST must be added.

 

INSTALLED_APPS

Also, 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. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.

 

By default, INSTALLED_APPS contains the following apps, all of which come with Django:

django.contrib.admin The admin site. Youll use it shortly.

django.contrib.auth An authentication system.

django.contrib.contenttypes A framework for content types.

django.contrib.sessions A session framework.

django.contrib.messages A messaging framework.

django.contrib.staticfiles A framework for managing static files.

 

Some of these applications make 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 migrate

The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app

Creating models

Now well define your modelsessentially, your database layout, with additional metadata

注:

A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data youre storing.

DRY Principle:Dont repeat yourself

Every distinct concept and/or piece of data should live in one, and only one, place. Redundancy is bad. Normalization is good.

目标:

In our simple poll app, well create two models: Question and Choice. A Question 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 Question.

修改: polls/models.py

from django.db import models
# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

 

Question1

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_text or pub_date) is the fields name, in machine-friendly format. Youll use this value in your Python code, and your database will use it as the column name.

 

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one

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 Question and Choice objects.

But first we need to tell our project that the polls app is installed.

 

Django apps are pluggable: You can use an app in multiple projects, and you can distribute apps, because they dont have to be tied to a given Django installation.

 

To include the app in our project, we need to add a reference to its configuration class in theINSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'.Edit the mysite/settings.py file and add that dotted path to the INSTALLED_APPS setting.

INSTALLED_APPS = [

    'polls.apps.PollsConfig',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

 

polls.apps.PollsConfig

class PollsConfig(AppConfig):
    name = 'polls'

Now Django knows to include the pollsapp. Let’s run another command:

$ python manage.py makemigrations polls

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

D:\code-github\mysite>python manage.py makemigrations polls

Migrations for 'polls':

  polls\migrations\0001_initial.py:

    - Create model Choice

    - Create model Question

    - Add field question to choice

There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

D:\code-github\mysite>python manage.py sqlmigrate polls 0001

BEGIN;

-- Create model Choice

CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

-- Create model Question

CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

-- Add field question to choice

ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";

CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));

INSERT INTO "polls_choice" ("choice_text", "question_id", "id", "votes") SELECT "choice_text", NULL, "id", "votes" FROM "polls_choice__old";

DROP TABLE "polls_choice__old";

CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");

COMMIT;

Now, run migrate again to create those model tables in your database:

D:\code-github\mysite>python manage.py migrate

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, polls, sessions

Running migrations:

  Applying contenttypes.0001_initial... OK

  Applying auth.0001_initial... OK

  Applying admin.0001_initial... OK

  Applying admin.0002_logentry_remove_auto_add... OK

  Applying contenttypes.0002_remove_content_type_name... OK

  Applying auth.0002_alter_permission_name_max_length... OK

  Applying auth.0003_alter_user_email_max_length... OK

  Applying auth.0004_alter_user_username_opts... OK

  Applying auth.0005_alter_user_last_login_null... OK

  Applying auth.0006_require_contenttypes_0002... OK

  Applying auth.0007_alter_validators_add_error_messages... OK

  Applying auth.0008_alter_user_username_max_length... OK

  Applying polls.0001_initial... OK

  Applying sessions.0001_initial... OK

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database

 

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:

[1]Change your models (in models.py).

[2]Run python manage.py makemigrations to create migrations for those changes

[3]Run python manage.py migrate to apply those changes to the database.

The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also useable by other developers and in production.

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:

$ python manage.py shell

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 yourmysite/settings.py file.

注:You must run python from the same directory manage.py is in, or ensure that directory is on the Python path, so that import mysite works.

D:\code-github\mysite>python manage.py shell

IPython 4.1.2 -- An enhanced Interactive Python.

?         -> Introduction and overview of IPython's features.

In [1]: import django

In [2]: django.setup()

Once you’re in the shell, explore the database API

In [1]: import django

In [2]: django.setup()

In [3]: from polls.models import Question, Choice

# No questions are in the system yet. >>> Question.objects.all()

In [4]: from django.utils import timezone

In [5]: q = Question(question_text="What's new?", pub_date=timezone.now())

In [6]: q.save()

# Create a new Question.

# 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.

# Save the object into the database. You have to call save() explicitly.

# Access model field values via Python attributes.

In [7]: q.id

Out[7]: 1

In [8]: q.question_text

Out[8]: "What's new?"

In [9]: q.pub_date

Out[9]: datetime.datetime(2016, 10, 27, 8, 18, 29, 785798, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save().

In [10]: q.question_text = "What's up?"

In [11]: q.save()

In [12]: Question.objects.all()

Out[12]: <QuerySet [<Question: Question object>]>

改进:

t’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin

修改之后:

from django.db import models
from django.utils.encodingimportpython_2_unicode_compatible
from django.utils import timezone
import datetime
@python_2_unicode_compatible  # only if you need to support Python 2
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
@python_2_unicode_compatible  # only if you need to support Python 2
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

测试一下:

In [13]: from polls.models import Question, Choice

In [14]: Question.objects.all()

Out[14]: <QuerySet [<Question: Question object>]>

In [15]: Question.objects.filter(id=1)

Out[15]: <QuerySet [<Question: Question object>]>

In [16]: Question.objects.filter(question_text__startswith='What')

Out[16]: <QuerySet [<Question: Question object>]>

In [17]: from django.utils import timezone

In [18]: current_year = timezone.now().year

In [19]: Question.objects.get(pub_date__year=current_year)

Out[19]: <Question: Question object>

In [20]: q = Question.objects.get(pk=1)

In [21]: q.was_published_recently()

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-21-3ba4aeb6d002> in <module>()

----> 1 q.was_published_recently()

AttributeError: 'Question' object has no attribute 'was_published_recently'

In [22]: q

Out[22]: <Question: Question object>

In [23]: q.choice_set.create(choice_text='Not much', votes=0)

Out[23]: <Choice: Choice object>

In [24]: q.choice_set.create(choice_text='The sky', votes=0)

Out[24]: <Choice: Choice object>

In [25]: c = q.choice_set.create(choice_text='Just hacking again', votes=0)

In [26]: c.question

Out[26]: <Question: Question object>

In [27]: q.choice_set.count()

Out[27]: 3

In [28]: Choice.objects.filter(question__pub_date__year=current_year)

Out[28]: <QuerySet [<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]>

In [29]: c = q.choice_set.filter(choice_text__startswith='Just hacking')

In [30]: c.delete()

Out[30]: (1, {'polls.Choice': 1})

In [31]:

Introducing the Django Admin

Creating an admin user

D:\code-github\mysite>python manage.py createsuperuser

Username (leave blank to use 'clark'): admin

Email address: xu_chl@163.com

Password:

Password (again):

This password is too short. It must contain at least 8 characters.

This password is too common.

Password:

Password (again):

Superuser created successfully.

Enter the admin site

http://127.0.0.1:8000/admin/

 

Make the poll app modifiable in the admin

Just one thing to do: we need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:

polls/admin.py

from django.contrib import admin
# Register your models here.
from .modelsimportQuestion
admin.site.register(Question)

Explore the free admin functionality


 

 

 

 

 

**************************************************************** 欢迎转发,注明原文:blog.csdn.net/clark_xu   徐长亮的专栏** 谢谢您的支持,欢迎关注微信公众号:clark_blog **************************************************************

 

 

1 0
原创粉丝点击