Django beginner manual 1-project and application creation and simple database operations

Source: Internet
Author: User

Create a project

 django-admin.py startproject mysite
1. directory structure
Mysite/# project name manage. py # file mysite/# actual project folder _ init __. py # empty file, telling python that this directory is a python package settings. py # the configuration file urls of the project. py # project URL declaration, which is the dispatch file wsgi. py # project wscgi entry
2. Start the development Machine

It is only used in the development environment and cannot be used in the production environment!
Development Environment supports hot start

Python manage. py runserver # default 8000 # If the host wants to access the VM, specify the IP address and port python manage. py runserver 0.0.0.0: 8000.
3. Database

Requirement MySQLdb

pip2.7 install mysql-python -i http://pypi.douban.com/simple

Set in the settings. py file

# DATABASES = {'default': {# 'engine': 'django. db. backends. sqlite3 ', # 'name': OS. path. join (BASE_DIR, 'db. sqlite3 '), 'Engine': 'django. db. backends. mysql ', 'name': 'test', 'user': 'root', 'Password': '123', 'host': '123456. 0.0.1 ', 'Port': '000000', }}# modify the time zone # TIME_ZONE = 'utc' TIME _ ZONE = 'Asia/Shanghai' # default value: appsINSTALLED_APPS = ('django. contrib. admin ', # manage the page 'django. contrib. auth ', # permission system 'django. contrib. contenttypes ', # Content Framework 'django. contrib. sessions ', # callback framework 'django. contrib. messages ', # message framework 'django. contrib. staticfiles ', # manage static Content Framework) # This command will install the above app and generate the corresponding table, where the system administrator account and password python manage are created. py syncdb
Create model

The app completes a specific function, such as a Weibo system, a public record database, or a simple voting program.
A project is a special website composed of several configuration files and many apps.
A project can contain many apps, and an app can be used for multiple projects.

python manage.py startapp polls

This will generate

polls/    __init__.py    admin.py    models.py    tests.py    views.py

First, define the model.
A model is an independent and limited resource of data. It includes the necessary fields and actions of the data to be stored.
Django follows the DRY principle, that is, Don't repeat youself-each independent concept or data is stored in one place and saved in one copy.
Define all models. for voting, create a vote and select two models. The vote includes one question and one launch date, and select the selected content and the voting count. Each choice should be associated with a vote.

    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 Model corresponds to a class, each class inherits from models. Model, and each class corresponds to a table.
Each class member has its own type for the columns in the table. Some parameters are required, such as max_length. They are not only the database mode, but also page verification. The default value of the integer type is optional.
The relationships between the last classes are described by foreign keys. Note that poll will be automatically added to poll_id.

Activate model

Add the application in settings. py.

INSTALL_APPS = (    ...    ...    'polls',)

Then, enter the command to observe the SQL statement generated by models.

python manage.py sql polls

There are some additional commands to observe the actual structure.

Python manage. py validate # Check errors, especially after building the app model and then running syncdb before python manage. py sqlcustom polls # output custom SQL statementpython manage defined by the application. py sqlclear polls # It is necessary to DROP the TABLE statement python manage in the output application. py sqlindexes pollspython manage. py sqlall polls # output SQL sqlcustom sqlindexes set

Then run these statements and create them in the database. This statement is only used for the first creation.

python manage.py syncdb
Call APIs to work
# Enter python manage in the interactive interface. py shell> from polls. models import Poll, Choice # Show all instances >>> Poll. objects. all () [] >>> from django. utils import timezone # create an object >>> p = Poll (question = "What's new? ", Pub_date = timezone. now () # Save to database> p. save () # p. question and so on. Check the class member function and save the modification. >>> Poll. objects. all () [<Poll: Poll object>] # This is because _ unicode _ is not set, class Poll (models. model ):#... def _ unicode _ (self): # Python 3: def _ str _ (self): return self. question # output> Poll. objects. all () [<Poll: What's new?>] # Search for the database and filter (double-underline after the class member name, you can add a variety of comparisons) # get can be used directly for search, where pk can be used to find the primary key, PrivateKey >>> Poll. objects. filter (question _ startswith = 'whe') [<Poll: What's up?>] >>> Current_year = timezone. now (). year >>> Poll. objects. get (pub_date _ year = current_year) <Poll: What's up?>

Because Poll is the foreign key of Choice, Poll has the following member functions:

>>> P. choice_set.all () []> c = p. choice_set.create (choice_text = 'just hacking again ', votes = 0) >>> p. choice_set.all () [<Choice: Not much>, <Choice: The sky >,< Choice: Just hacking again>] >>> p. choice_set.count () 3 # Choice also has the following member variables> c. poll <Poll: What's up?> # Delete a record >>> c = p. choice_set.filter (choice_text _ startswith = 'just hacking') >>> c. delete ()

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.