To build the simplest Django framework instance under Python

Source: Internet
Author: User
Tags sqlite sqlite database
Accustomed to the Java code, recently thinking about learning new language to play, just a friend is learning Python, so also want to learn Python play, Python has a web framework Django, these two days also tried
Found also quite good, to build their own Django experience to share, give the novice a reference, haha


Operating Environment
Windows 7 (64-bit) + Python 2.7 + Django 1.7.1
1. Installing the Django Framework
Of course you have to have the Python environment, for the friends who learn python this is not much to say ~ ~
I'm using the Setuptools tool to install, Setuptools is a common installation tool for Third-party modules installed in Python
1.1 Install the Setuptools tool (if it can be installed to skip directly)
Download ez_setup.py from this address first:
Https://pypi.python.org/pypi/setuptools#windows (at the bottom of the page)
I downloaded the setuptools-7.0.zip, unzip it, put the extracted setuptools-7.0 file into a directory, and I assume it's placed in the C:\workspace directory
Open command line cmd, switch to C:\workspace\setuptools-7.0 in Cmd, that is, setuptools-7.0 installation directory
To run the command:
Python ez_setup.py
The command installs the Setuptools tool, installs the Scripts directory under your Python installation directory (my C:\Python27\Scripts), and sees Easy_install.exe files
Note Add the Scripts directory (my C:\Python27\Scripts) under the Python installation directory to the environment variable path, or the following Easy_install command will complain
1.2 Installing the Django Framework
In cmd, enter:
Easy_install Django
Some installation process may be prompted by the lack of VC + + package, according to the hint URL (i forgot ~) download package, I downloaded is vcforpython27.msi, install VC + + before performing installation
This automatically installs the Django, is not very convenient, haha


2. Create the Django project, which is assumed to be created under C:\workspace\djangoTest (and Java is a little different, Java is directly create the project on it, Python is to create the project and then create the app in the project)
Entering the C:\workspace\djangoTest directory, enter:
Django-admin startproject Mytodo #网上很多是python django-admin.py startproject Mytodo, different versions may have subtle differences in command
We created the Mytodo project.


3. Start the Debug server
Enter C:\workspace\djangoTest\djangoTest\mytodo directory:
CD Mytodo
Then enter:
Python manage.py runserver
Enter Http://127.0.0.1:8000/in the browser to see if you can access the page


4. Create app
Input command: Python manage.py startapp todo
Under the Mytodo project, you created an app called Todo
Edit mytodo/settings.py file, add entries in Installed_apps todo
Installed_apps = (
' Django.contrib.auth ',
' Django.contrib.contenttypes ',
' Django.contrib.sessions ',
' Django.contrib.sites ',
' Todo ',
)
That is, add a line of Todo at the end (some version is the +app name of the project name, i.e. Mytodo.todo)
Again enter: Python manage.py runserver to see if your app is configured, develop a good habit of writing and testing, haha ~


5. Configuration database
Django defaults to using the SQLite database as the background database, still opening the mytodo/settings.py, and you can see the following paragraph:
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.sqlite3 ',
' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),
}
}
This is the Django Project database configuration, the default is using SQLite, we use the default configuration, install the SQLite database, do not need to modify the configuration file
Hear and install the database, we must feel very complex, in fact, in Python to install the three-party module, database what is very simple, a command can be done ~ ~
Enter command:
Easy_install Pysqlite
This will install the SQLite database
After installing the database, we also test and enter the command:
Python manage.py syncdb
Successfully prompted to install successfully, open the Mytodo directory to see if there is a Db.sqlite3 file, which is the configuration of the above database file
In this case, a hint that our commands are entered in the cmd command line, not in the python interactive environment Python shell input, everyone attention ~ ~


The above are all configured with a variety of environments, the following is the formal code (of course, there are configuration), before writing to explain, Django inside is also the MVC pattern, just and Java inside the
Not too, the C (ie Controller) in MVC is not called Controller in Django, but view, which requires attention, and the other is that Django implements the ORM framework, and we don't need to write it ourselves.
To make the code for the database, call the Django-provided model layer method.
Our process is also very simple, is the user input an address, submitted to the Controller view index method, the index method calls model Layer mode processing, get results, and then jump to the index page display results
is a most simple process, we should all understand it, haha ~ ~


6. Configure the Model layer
Add Class Todoentry to the todo/models.py file:
Class Todoentry (models. Model):
Task = models. Charfield (max_length=120)
Status = Models. Integerfield ()
Create_date = models. Datetimefield (' Create date ')


def __unicode__ (self):
Return Self.task

Then run the following command:
Python manage.py makemigrations Todo # (commands are preceded by Python, some versions are not Python)
The command generates a submit script in the Todo/migrations directory, opens the Todo/migrations directory, and looks for a 0001_initial.py file that was just generated
Python manage.py sqlmigrate todo 0001 #该命令可以查看刚刚的脚本的sql语句, you can not perform
Python manage.py Migrate
The command will actually manipulate the database, that is, generate the corresponding table in the database


7. Configure the View layer (Controller)
Edit the todo/views.py file to implement the INDEX function:
# ' Todo.views.index '

def index (Request):
All_todo_list = TodoEntry.objects.all (). order_by ('-create_date ')


Return Render_to_response (' todo/index.html ', {' all_todo_list ': all_todo_list}, context_instance = RequestContext ( Request))

The function means to remove all the records from the Todoentry table to display to the Todo/index.html page, to use the Todoentry class in the function, and to use two variables Render_to_response,requestcontext
So here we want to import the corresponding variable, add the following code at the beginning of the todo/views.py file, import the module variable
From models import Todoentry
From django.shortcuts import Render_to_response,requestcontext


8. Configure URL
Edit the Urlpatterns in mytodo/url.py and add the following configuration:
URL (r ' ^todo/$ ', ' Todo.views.index ')
This configuration means that when Http://127.0.0.1:8000/todo is entered in the browser (that is, the app root directory), the index function is skipped to the view layer (that is, views.py)


9. Configuration template
First create a new page index.html in the Todo directory, and enter the following code:
{% if all_todo_list%}
{% for entry in all_todo_list%}
<p> {Entry.task}}
<a href= "/todo/del/{{entry.id}}/" > Delete </a>
</p>
{% ENDFOR%}
{% Else%}
<p>no Todo entry are available.</p>
{% ENDIF%}

Then edit the mytodo/settings.py file and add the following configuration:
Template_dirs = [Os.path.join (Base_dir], that is, the pages in the TODO directory will be rendered

You can also create a new templates directory under Todo, put index.html in the Templates directory, and configure the following:
Template_dirs = [Os.path.join (base_dir, ' templates ')]
It means that the pages in the todo/templates (the root directory is the Todo) will be rendered


10. Test
Open the browser, in the address bar input: Http://127.0.0.1:8000/todo, if the page is normal, it means success

In his own Django environment, referring to a Daniel's blog http://www.cnblogs.com/weichsel/archive/2012/10/15/2724108.html, Daniel's blog more refined
We can also directly according to Daniel's blog to operate ~ ~



Related Article

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.