Django Learning Notes (ii) model of app creation

Source: Internet
Author: User

Through the example study, constructs a poll (polls) application, the target result contains two site, one site is used to display the poll question as well as the poll result (will display the website), another site is used to manage the poll instance the additions and deletions to change (that is, the background content management CMS ).

1. Create a project

django-admin.py Startproject MySite

In the current directory, a MySite project directory is created. So where do we put the code better? May be placed under the OS's own server root directory (document root), such as/var/www, so that we can access the code directly from the browser. However, the security of this code is not very good, so it is recommended to be placed in a directory other than the server root directory.

Engineering Structure:

1   mysite/2 manage.py3 mysite/4 __init__.py5 settings.py6 urls.py7 wsgi.py8 9   the outer mysite directory, which is the entire container of the project, makes no sense to Django, so it's OK to change whatever name you want.Ten   manage.py is a command-line tool to manage the entire project,--help to view the corresponding commands. One   the MySite directory of the inner layer is a package for the project, and also an entry point for the project, and we need to use this package name to refer to the various configurations and variables we need. A   mysite/__init__.py: Description The current directory mysite/is a python package. -   mysite/settings.py: project configuration file -   mysite/urls.py: Routing scheduling for projects theMysite/wsgi.py:wsgi Server entry point (how to deploy with Wsgi)

2. Internal Development Server

python manage.py runserver

Enter the project directory and execute the above command, and the Django Internal Development server (a lightweight server written purely by Python) will start. Access localhost:8000 in the browser,

We will see a "Welcome to Django", it worked.

Note: Change the Listener port command:python manage.py runserver 8080 change listener All public IPs: python manage.py runserver 0.0.0.0:8000

3. Database Settings

Change databases ' default ' option

engine-django.db.backends.*, Oracle, MySQL, or sqlite3, etc., other backend such as (south.db.) sql_server.pyodbcname– database name, if using Sqlite3, This should be the absolute path to the file (e.g.c:/homes/user/mysite/sqlite3.db). Note that there is a slash instead of a backslash here. user– database user name (SQLite does not need) password– database password (SQLite does not need) host– database host Address "127.0.0.1" or "**.**.com"
Port-Host open port is typically 3306 if you use MySQL or PostgreSQL, you first have to execute the CREATE DATABASE command on the database server port, make sure that the database is present in the settings, and that SQLite does not need to synchronize the data when it is created by default.

Python manage.py syncdb

Django automatically synchronizes all of the apps in the Installed_apps to the database, creating the appropriate data tables for each app, while the first execution creates a Super admin super that manages the data tables. Administrator.

4. Model creation

All of the apps used in the project are actually made up of Python's packages.

The difference between project and app:

An app is a Web application designed to do a particular job, such as blogs, session records, and so on, and project is a collection of configuration files and a series of apps. There can be multiple apps in a project, and an app can exist in more than one project (reusability). An app can be placed anywhere, just add it to the Python path, so the project can be found.

Python manage.py Startapp Polls

After execution, a polls directory is created under the project root, including __init__.py view.py models.py etc. If you want to include an app in a separate directory, such as/mysite/apps, go to the Apps directory, Python. /manage.py Startapp Polls, but later references are to be imported from the apps, from Apps.polls.models import Poll, Choice.

Below, enter the following code in polls\models.py:

 from  django.db import   models  class   Poll (models. Model): Question  = models. Charfield (Max_length=200 = models. Datetimefield ( "  "  class   = models. ForeignKey (Poll) Choice_text  = models. Charfield (Max_length=200 = models. Integerfield (default=0) 

The code is clear, the two classes inherit from the Django.db.models.Model, the variables are filed instances, and the relationships of the two classes are models. ForeignKey (many to one) determines that poll is the foreign key of choice, that is, a poll corresponds to more than one choice.

Configure polls to Installed_apps in the setting.py file (do not forget to separate each app configuration with a comma), then execute Python manage.py syncdb and create a good polls in the database The app's data sheet. Python manage.py SQL polls, manage.py validate, and other commands can be used to further explore how Django works in the background.

5. DB API interaction

Python manage.py Shell

After you run this command, the manage.py command sets the django_settings_modul environment variable, which provides a DJANGO reference to the Python global path. The resources we need are sourced.

1>>> fromPolls.modelsImportPoll, Choice#Import The Model classes we just wrote.2 #No Polls is in the system yet.3 4>>>Poll.objects.all ()5 []6 7>>> fromDjango.utilsImportTimeZone8>>> p = Poll (question="What ' s new?", pub_date=Timezone.now ())9 #Save the object into the database. You have the call Save () explicitly.Ten>>>P.save () One  A>>>p.id -1 -  the>>>Poll.objects.all () -[<poll:poll Object>]

Wait a moment, [<poll:poll Object>] Display is not clear, the intuitive feeling is not helpful, the solution is: in models.py for different classes to add a __unicode__ method, in Python3, Because the uniform processing of strings is regulated, it needs to be replaced with __str__.

1 classPoll (models. Model):2     # ...3     def __unicode__(self):#Python 3:def __str__ (self):4         returnself.question5 6 classChoice (models. Model):7     # ...8     def __unicode__(self):#Python 3:def __str__ (self):9         returnSelf.choice_text

The python2.* version does not have Unicode and ASCII-encoded processing, so errors often occur for strings, such as the return self.id in __unicode__, and the traversal of output Unicode data in cmd, which is the cause of the codec error.

Reload the Python manage.py shell,

>>> fromPolls.modelsImportPoll, Choice
#make sure __unicode__ () is working.>>>Poll.objects.all () [<poll:what's Up?>]#The following statement is equivalent to Poll.objects.get (id=1).>>> Poll.objects.get (pk=1)<poll:what's up?>>>> p = Poll.objects.get (pk=1)#displays all P-related choice collections-so far none.>>>P.choice_set.all () []#create three instances of choice.>>> 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)#foreign keys can be accessed through choice instances, and only "What's Up" is returned due to __unicode__.>>>C.poll<poll:what's up?>#gets the choice collection under all p.>>>P.choice_set.all () [<choice:not much>, <choice:the Sky>, <choice:just hacking again>]>>>P.choice_set.count ()3

That ' s it.

Django Learning Notes (ii) model of app creation

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.