Introduction to the Django Framework environment deployment and application writing under Windows Python

Source: Internet
Author: User
Environment construction
1. Download the required packages:
(1) Python installation package
(2) Django installation package
The following 2 packages are actually installed with the Python Package management tool, which will be used when installing the Django Documentation Package module later, and the download site is PyPI
(1) Setuptools.exe
(2) Pip

2. Install the required packages:
Python installation package is Exe,setuptools is also exe, so directly double-click Install, first install
Django, Pip is the Python module package: The installation of the first decompression, and then enter the directory after the use of the command: Python setup.py install installation can be

3. Test Python and Django
Python and Setuptools because it is the EXE installation method, has helped you to add environment variables, after installation can be used directly
Django, PIP installation requires manually adding their installation directories to environment variables
New cmd: Enter Python, see Python interactive interpreter is not a problem
Enter django-admin.py--help to see the use of the help tips to indicate that the installation was successful

4. Establish the first Django project:
The following cmd command creates a Django project Djangoproject1 in the current directory:

django-admin.py Startproject Djangoproject1

There are 4 files in this project directory:

__init__.pymanage.py   # # #功能与django-admin.py the same file, but this is mainly used to manage the current project settings.py   # # #当前项目的设置文件, such as: WebApp directory settings, Database connection settings, template directory settings, etc. urls.py       # # #当前项目url导航的设置, with a regular matching pattern this matches the URL rule and maps to the specified file to process the request

5. Install a Django-brought admin app that installs a WebApp
Modify the following content in the setting.py file:

DATABASES = {'   default ': {     ' ENGINE ': ' Sqlite3 ', #设置使用sqlite3数据库     ' NAME ': R ' C:\Users\ .... \test.db ',           # sqlite3 file path     ' USER ': ', # not           used with sqlite3.     ' PASSWORD ': ',         # not used with sqlite3.     ' HOST ': ',           # Set to empty string for localhost. Not used with sqlite3.     ' PORT ': ',           # Set to empty string for default. Not used with Sqlite3.   } }   Installed_apps = (   ' Django.contrib.auth ',   ' django.contrib.contenttypes ',   ' Django.contrib.sessions ',   ' django.contrib.sites ',   ' django.contrib.messages ',   ' Django.contrib.staticfiles ',   # uncomment the next line to enable the admin:   ' django.contrib.admin ',  # # Cancel the original comment   # uncomment the next line to enable admin documentation:   ' Django.contrib.admindocs ',  

Modify the following contents in the urls.py ask:

# Uncomment the next lines to enable the Admin:from django.contrib Import Admin # #取消注释 Admin.autodiscover ()  # #取消注 Release    # uncomment the Admin/doc line below to enable admin documentation:   URL (r ' ^admin/doc/', include (' Django.contrib.admindocs.urls '),  # # #取消注释    # Uncomment the next line to enable the admin:   URL (r ' ^admin/', Include (Admin.site.urls)),  

6. Sync Admin Application database:
Use the command in the Project home directory:

manage.py syncdb

You will be prompted to create a super user, enter Yes and follow the prompts to create an account.

7. Test Admin Application:
To start the Django service with a command:

Enter address in browser: http://127.0.0.1:8000/admin/
If the login interface indicates that the Admin app was successfully installed, log in using the account created in step 6th

8, install the admin document module:
Command Line Input:

Pip Install Docutils

Restart the Django service when the installation is complete, access address http://127.0.0.1:8000/admin/doc/

9. Use and learn the admin application:
This application is mainly used to manage the application of the project, the same can be very important to manage the database content, if you want your project can also be managed here, you need to make a configuration, there will be related actions
By default, it has the following functions: User, user group to manage Admin app, add site

10. Create your own application:
Use commands in the project home directory:

manage.py Startapp MyApp

The command creates an app's directory MySite under the current directory, with the following files:

__init__.pymodels.py   # #用于创建数据模型的, that is, the design of the database structure, in this configuration to the database module, Django will automatically help you to create the corresponding database table structure views.py    # #视图文件, Used to respond to a user request and return results after processing, which mainly writes the response function of the request event

11, installation of their own applications:
Modify the settings.py file as you would install the Admin app

Installed_apps = (     ...     ') Djangoproject1.myapp ',    

12. Create the first page:
Modify the views.py file in the MySite directory as follows:

From django.http import HttpResponse  def Home (Request):   

13. Set URL Request page:
Modify the urls.py content as follows:

Urlpatterns = Patterns ("',   # Examples:   

14. Test your application:
Restart the Django service,

manage.py Runserver

Visit: http://127.0.0.1:8000
If it appears: Hello Django indicates a successful setup


First app implementation
all we have to do is fill in the content as the environment builds up. That is, the actual content of the page, such as: page content, such as the content of the database, such as the content of the module, such as Css,js content, then in Django is how to integrate these, recorded here.
1, create a pattern:
mode is actually the entire Web site data model, that is, the structure of the database, that is, the data table structure, so creating a pattern is to design a data table, but in the Django pattern in the form of code to represent the pattern, Then it will help you automatically generate a response to the data table and the corresponding relationship, but also to support the database is a unified representation, that is, compatibility is good, is not very convenient Ah! See below:
Writing models.py files in the app directory

From django.db Import Models  class location (models. Model): City   = models. Charfield (max_length=50) state   = models. Charfield (max_length=50, Null=true, blank=true)   country = models. Charfield (max_length=50)   def __str__ (self):     if self.state:       return "%s,%s,%s"% (Self.city, self.state, Self.country)     Else:       return "%s,%s"% (self.city, self.country)  class Job (models. Model):   pub_date = models. Datefield ()   Job_title = models. Charfield (max_length=50)   job_description = models. TextField () Location   = models. ForeignKey   def __str__ (self):     

2. Let the mode take effect:
After the pattern has been designed you can use it, let it work for you, to see if the schema created by the correct command is: manage.py SQL App_dir, so you can view the table structure of the prototype. After checking out the prototype of the table structure, the command is: manage.py syncdb, this is actually the real database in the table.

3, how to apply the mode:
Mode is still in effect is how to apply it, that is, to obtain the data to serve us, in the views.py file includes the following code to invoke the specific data table;

From django.template import Context, loader from django.http import HttpResponse from myapp.models import Job   def home (request):   object_list = Job.objects.order_by ('-pub_date ') [:]   str_count = "The Count of Job table is%s"% Job.objects.count ()   Str_job_desc = "
". Str (Join (Job.objects.all ())) return HttpResponse (Str_count +"

Restart Django, Access http://127.0.0.1:8000, if the character information appears to be correct, only then shows the total data data is 0, the content is empty

4. Configure my app in admin:
There is no data on the above, then create some data: one is to write their own SQL to build, but another way is to build the data in the admin application, of course, the first is to configure the admin to manage the application I created. Create a new admin.py file in my app directory with the following contents:

From django.contrib Import admin from Mydjango.myapp Import models  class Documentadmin (admin. Modeladmin):   Pass  class commentadmin (admin. Modeladmin):   Pass  

By restarting Django and accessing Http://127.0.0.1:8000/admin, you can see that the data in my app can be managed here.

5. Manage my apps in admin:
After setting up my app in admin, you can add data to my app via admin. Specifically, click Add, enter content, save. When we get the data, we'll go back to the homepage and see if the content is on the page.

6. Start setting up the template:
When the content is small, we can write each page on its own, but when the page is more, and there are many of the same parts, we want to not write the same things, then the template is to solve such problems, the emergence of the The way to configure a template in Django is to modify the following in the settings.py file in the project home directory:

Template_dirs = (   

7. Create template file:
In the template directory of the settings.py file settings to create a new template file, template files are actually HTML files, but the contents of which contain some special placeholders, in the actual application will replace the contents of it, which is implemented in the code data, and the template can also inherit, this is also more useful, like the program's The finer the chunks of code are, the better the reusability. Examples are as follows:
The contents of the base.html file in the template home directory

      Company Site: {% block title%}page{% Endblock%}   {% block Extrahead%} {% Endblock%}       {% block content%} {% Endblock%}    base.html content under Template/mytemp directory [HTML] view plain copy{% extends "base.html"%}  {% block Extrahead%}   

Job_list.html under the Template/mytemp directory

{% extends "jobs/base.html"%}  {% block title%} Job list{% endblock%}  {% block content%}   

Job List

    {% for job in object_list%}
  • {{Job.job_title}}
  • {% ENDFOR%}

Job_detail.html under the Template/mytemp directory

{% extends "mytemp/base.html"%} {% block title%} Job detail{% endblock%}{% block content%}  

Job Detail

{{Job.job_title}} - {{job.location}} Posted: {{job.pub_date|date: ' D-m-y '}} {{job.job_description}} {% endblock%}


8. Apply Template file:
In Django is the specific reference template in views.py, as shown below:
Method One:

From django.template import Context, loader from django.http import HttpResponse from myapp.models import Job  def home (request):   object_list = Job.objects.order_by ('-pub_date ') [: ten]   t = loader.get_template (' Mytemp/job_ List.html ')   C = Context ({     ' object_list ': Object_list,     })   

Method Two:

From django.shortcuts import get_object_or_404, render_to_response from myapp.models import Job  def home (Request, job_id):   job = get_object_or_404 (Job, pk=job_id)   return render_to_response (' mytemp/job_detail.html ',                

9, the final views.py file contents are as follows:

From django.template import Context, loader from django.http import HttpResponse from myapp.models import Job from Django. Shortcuts import get_object_or_404, Render_to_response  def Home (Request):   return HttpResponse ("Hello Django" )     def index (request):    object_list = Job.objects.order_by ('-pub_date ') [: ten]    t = loader.get_template (' Mytemp/job_list.html ')    C = Context ({      ' object_list ': Object_list,      })    return HttpResponse (T.render (c )        def detail (request,job_id):    job = get_object_or_404 (Job, pk=job_id)    return Render_to_response (' Mytemp/job_detail.html ',                 {' object ': Job})  

9, configure the index, detail the URL of the view, in urls.py add the following:

URL (r ' ^job/$ ', (' Mydjango.myapp.views.index ')), url (r ' ^job/(? P
 
  
   
  \d+)/$ ', (' Mydjango.myapp.views.detail ')),
 
  

Then, after restarting the service, access the http://127.0.0.1:8000/job/

OK, all the structures have been used, and the rest is to come up with an interesting project to get started!

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