Django1.7 Learning Notes (i)

Source: Internet
Author: User

Recently in learning Django, English is not good, I found some Chinese information, the most complete is the Django Book 2.0 Chinese version of the link: http://docs.30c.org/djangobook2/index.html, try to look at it is not bad, But the book is about the Django1.1 version, known as compatible Django1.9, I use the latest version of Django1.7, or there are some differences, so, combined with this book and Django1.7 official documents, coupled with some of their own experiments and understanding, Django1.7 will be the development of the process of recording down, I hope to help you, I student party, rookie, welcome Daniel Guide!

Development environment: Ubuntu Kylin14.10,python 2.7.8,django1.7,mysql5.5,ide Pycharm3.13


1. Install Python and Django

Python ubuntu itself, the default is 2. X version, Django can be downloaded via #easy_install Django or to the official website, this is not much to say


2. Create a project

After you install Django, you will automatically install the Django-admin command, if not, you will be prompted to install it, and then select a folder to build the project, here is MySite, execute the command

$django-admin startproject MySite

The MySite folder is automatically established and the folder directory structure is as follows:

mysite/#只是Django项目的容器, you can name it casually.

manage.py #命令行工具, used to interact with Django, IMPORTANT!!!

mysite/#Python的项目管理包, so need __init__.py,

__init__.py #初始化文件, don't worry.

settings.py #Django的配置文件

urls.py #Django的URL配置文件

wsgi.py #WSGI兼容的Web服务器的一个入口点 to meet your project

If you don't want to be so troublesome, you can use the IDE directly, I use the pycharm, also good, directly to build a Django project, the following to say what the app will be automatically built, the following figure:



Three. Database Settings

Now mainly editing setting.py and using the manage.py tool, open setting.py file, edit, first find the Databases dictionary, django default database SQLite, if the use of SQLite will not be configured, If you want to use a different database, you need to configure the mysql5.5 database. This is my configuration:

DATABASES = {
' Default ': {
# ' ENGINE ': ' Django.db.backends.sqlite3 ',
# ' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),
' ENGINE ': ' Django.db.backends.mysql ', #数据库类型
' NAME ': ' Django ', #数据库名称
' USER ': ' Root ', #用户名
' PASSWORD ': ' Root ', #数据库密码
' HOST ': ' 127.0.0.1 ', #主机地址, this is the local
' PORT ': ' 3306 ', #数据库端口号
}
}

Here in the setting can modify the time zone and language, modified to China's time zone and the Chinese are as follows:

Language_code = ' ZH-CN '
Time_zone = ' Asia/shanghai '


Also, note that the Installed_apps is set at the top of the file. Holds the name of all Django applications that are activated in this Django scenario. Applications can be used in multiple projects, and you can use them through packaging and other people distributing them in their projects,

By default, Installed_apps contains the following applications, all of which are generated by the Django default: Django.contrib.admin-admin site. Django.contrib.auth-an authentication system. Django.contrib.contenttypes-Framework for content types. Django.contrib.sessions-a session framework. Django.contrib.messages-Message Delivery framework. Django.contrib.staticfiles-the framework for managing static files.

These applications need to create a table in the database, so create a table by using the command:

# python manage.py Migrate

The results of the successful operation are as follows:

Operations to perform:
Apply all migrations:admin, ContentTypes, Auth, Sessions
Running Migrations:
Applying contenttypes.0001_initial ... Ok
Applying auth.0001_initial ... Ok
Applying admin.0001_initial ... Ok
Applying sessions.0001_initial ... Ok

#

The corresponding table has been automatically established in the database at this time.

Incidentally, if the MySQL database can not be inserted in Chinese problems, you can look at my another blog: Ubuntu under MySQL can not display Chinese solution: http://blog.csdn.net/dj1174232716/article/details/40746289

Four. Development Server

Start the Django server now:

$ python manage.py runserver

It can then be accessed through Http://127.0.0.1:8000/, the default port is 8000, and no other address is allowed, and can only be accessed locally. But by:

$ python manage.py runserver 8080 modifies the port number and can also be achieved by:

$ python manage.py runserver 0.0.0.0:8000 can be accessed by other hosts.


Five. Create a model

Each application you write in Django contains a Python package, followed by certain conventions. Django provides a utility that automatically generates a basic directory structure for an application, so you can focus on writing code instead of creating a directory. A project can contain multiple applications. An application can be in multiple projects.

Now we will create an application (APP) by:

$python manage.py Startapp Polls we created an application called polls, and the directory structure became the following structure:

mysite/#只是Django项目的容器, you can name it casually.

manage.py #命令行工具, used to interact with Django, IMPORTANT!!!

mysite/#Python的项目管理包, so need __init__.py,

__init__.py #初始化文件, don't worry.

settings.py #Django的配置文件

urls.py #Django的URL配置文件

wsgi.py #WSGI兼容的Web服务器的一个入口点 to meet your project

polls/

migrations/

__init_.py

__init__.py

admin.py

models.py

tests.py

views.py

Then try to build a database model:

polls/models.py

From django.db import Models


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)
    Choice_text = models. Charfield (max_length=200)
    votes = models. Integerfield (default=0)
The class name is the table name in the database, the property is a field, and the type and constraint of the field is set.


Six. Activation model

The Django model is required to be activated or installed after installation in settings.py, edited as follows:

mysite/settings.py

Installed_apps = (
    ' django.contrib.admin ',
    ' Django.contrib.auth ', '
    django.contrib.contenttypes ',
    ' django.contrib.sessions ',
    ' django.contrib.messages ', '
    django.contrib.staticfiles
    ', ' Polls ',
)
Add the last item polls one. Then run the following command:

$ python manage.py makemigrations polls

You will see the following:

Migrations for ' polls ':
0001_initial.py:
-Create Model Choice
-Create model question
-Add field question to choice

By running Makemigrations, you tell Django that you've made some changes to your model (in this case, you've made a new one) and you want to change the storage for a migration. And then through:

$ python manage.py sqlmigrate polls 0001

Let Django create the SQL statement by itself, and then pass the command:

$python manage.py Migrate

By performing these SQL executions and creating the corresponding table in the database, you will see the following hints:

Operations to perform:
Apply all Migrations:admin, contenttypes, polls, Auth, sessions
Running Migrations:
Applying polls.0001_initial ... Ok


Seven. Accessing the data in the database through the Django API

The data in the database can be accessed through Django-provided APIs without using SQL statements to read the data.

You can go to the Django-provided shell to manipulate the data:

$python manage.py Shell into the shell

If you don't want to use manage.py, no problem. Simply set the DJANGO_SETTINGS_MODULE environment variable mysite.settings, start a generic Python shell, and set up the Django:

>>> import Django
>>> django.setup ()
Now look at the code to see how Django uses the API to manipulate the data:

>>> from polls.models import question, Choice # import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all () [] # Create a new question.  # Support for time zones are 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'll do-right thing. >>> from django.utils import timezone >>> q = question (question_text= "What ' New?", pub_date= Timezone.now ()) # Save the object into the database.
You are have to call Save () explicitly. >>> Q.save () # Now it has ID. This is the might say "1L" instead of "1", depending # on which database for you ' re using. That ' s no biggie;
It just means your # database backend prefers to return integers as Python long Integer # objects.
>>> q.id 1 # Access model field values via Python attributes. >>> q.question_text "What ' s new?" >>> Q.pub_dAte datetime.datetime (2, num, 0, 0, 775217, tzinfo=<utc>) # change values by changing the attributes, then
Calling Save (). >>> q.question_text = "What ' s up?" >>> Q.save () # Objects.all () displays the questions in the Datab
Ase. >>> Question.objects.all () [<question:question Object>]

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.