Introduction to Python Django framework Environment deployment and application writing in Windows

Source: Internet
Author: User
This article mainly introduces how to deploy and compile the Django framework environment of Python in Windows. Django is a heavyweight MVC Framework in the Python framework, this article describes how to write a hellowworldweb application from the perspective of program deployment. For more information, see Environment Construction
1. download the required software package:
(1) python installation package
(2) django installation package
The following two packages are actually used to install the python package management tool, which will be used later when the django document package module is installed. The download website is pypi.
(1)setuptools.exe
(2) pip

2. Install the required software package:
The python installation package is exe, And the setuptools is also exe, so you can simply double-click to install it first.
Django and pip are python module packages: unzip the package before installation, and then run the command: python setup. py install to install the package.

3. Test python and django
Python and setuptools have added environment variables for you because they are installed using exe. After installation, you can directly use
After installing django and pip, you must manually add their installation directories to environment variables.
New cmd: Enter python. If you see that you can enter the python interactive interpreter, there is no problem with python.
Enter the django-admin.py -- help to see the help prompt indicating that the installation was successful

4. Create the first django project:
The following command creates a django project djangoproject1 in the current directory:

django-admin.py startproject djangoproject1

The project directory contains four files:

_ Init __. pymanage. py ### features the same file as the django-admin.py, but this is mainly used to manage the current project settings. py ### setting files of the current project, such as setting the webapp directory, setting the database connection, and setting the template directory. py ### set the url navigation of the current project. Use a regular expression matching the url rule and map it to the specified file to process the request.

5. Install the admin application that comes with django, that is, install a webapp.
Modify the following content in the setting. py file:

DATABASES = {'default': {'Engine ': 'sqlite3', # Set the sqlite3 database '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 ', # cancel the original comment)

Modify the following content in the urls. py file:

# Uncomment the next two lines to enable the admin: from django. contrib import admin # uncomment admin. autodiscover () # 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), ### cancel the Annotation

6. Synchronize the admin application database:
Run the following command in the main directory of the project:

manage.py syncdb

You will be prompted to create a super user. Enter yes and follow the prompts to create an account.

7. Test the admin application:
Run the following command to start the django service:

manage.py runserver 

Enter the address http: // 127.0.0.1: 8000/admin/in the browser/
If the logon page appears, the admin application is successfully installed. Log On with the account created in step 1.

8. Install the admin document module:
Command Line input:

pip install docutils

Restart the django service after installation. Access address: http: // 127.0.0.1: 8000/admin/doc/

9. Use and learn admin applications:
This application is mainly used to manage project applications. It can also be used to manage database content. If you want to manage your project as well, you need to configure it, related operations will be performed later
The default functions are as follows: Manage admin application users and user groups; add sites

10. Create your own application:
Run the following command in the main directory of the project:

manage.py startapp myapp

Command will create an app directory mysite under the current directory, which contains files:

_ Init __. pymodels. py ## used to create a data model, that is, to design the database structure. Here, the module is configured to the database. django will automatically help you create the corresponding database table structure views. py # view file, which is used to respond to user requests and return results after processing. The response function of the Request event is mainly written here.

11. install your own applications:
Modify the settings. py file like installing the admin application.

INSTALLED_APPS = (...... 'djangoproject1. myapp', ### add this sentence)

12. Create the first page:
Modify the views. py file in the mysite directory. The content is as follows:

from django.http import HttpResponse  def home(request):   return HttpResponse("Hello Django") 

13. Set the url request page:
Modify urls. py as follows:

urlpatterns = patterns('',   # Examples:   url(r'^$', 'djangoproject1.myapp.views.home', name='home'), ) 

14. Test your own applications:
Restart the django service,

manage.py runserver

Access: http: // 127.0.0.1: 8000
If "hello django" is displayed, the setting is successful.


First app implementation
After the environment is set up, we need to fill in the content. That is, the actual content of the webpage, such as the page content, such as the database content, such as the module content, such as css and js content, how can we integrate these content in django, record it here.
1. Create a mode:
The mode is actually the data model of the entire website, that is, the database structure, that is, the data table structure. Therefore, creating a mode is to design a data table, however, in the django mode, the code is used to represent the mode. Then, it will help you automatically generate the response data table and the corresponding relationship, and it is a unified representation of the supported databases, that is, the compatibility is good. Is it very convenient! For an example, see:
Compile the models. py file 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(Location)   def __str__(self):     return "%s (%s)" % (self.job_title, self.location) 

2. Enable the mode to take effect:
After the schema is designed, you can use it to help you. Check whether the correct command for the table created in the schema is manage. py SQL app_dir to view the table structure prototype. After checking the table structure prototype, run the following command: manage. py syncdb, which is actually used to create a table in the database.

3. How to apply the model:
After the mode still takes effect, you can apply it, that is, get the data to serve us. In the views. py file, you can call a specific data table by using the following code;

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')[:10]   str_count = "The Count of job table is %s"%Job.objects.count()   str_job_desc = "
".str(join(Job.objects.all())) return HttpResponse(str_count + "
" + str_job_desc)

Restart django and access http: // 127.0.0.1: 8000. If the characters are correct, the total number of data is 0 and the content is blank.

4. Configure My application in admin:
If there is no data in the above content, you can create some data: one is to write SQL statements by yourself; the other is to create data in the admin application, of course, the first step is to configure admin to manage the applications I created. Create an admin. py file in the my application directory with the following content:

from django.contrib import admin from mydjango.myapp import models  class DocumentAdmin(admin.ModelAdmin):   pass  class CommentAdmin(admin.ModelAdmin):   pass  admin.site.register(models.Location, DocumentAdmin) admin.site.register(models.Job, CommentAdmin) 

Restart django and access http: // 127.0.0.1: 8000/admin. The data in my application can be managed here.

5. Manage My applications in admin:
After setting my application in admin, you can use admin to add data to my application. Click Add, input, and save. After the data is available, we can go back to the home page to see if the page content is based on the content?

6. Start to set the template:
When there is less content, we can write each page by ourselves. But when there are more pages and there are many identical parts, we hope we can not write the same things, the template appears to solve this problem. In django, you can configure the template in the settings of the main directory of the project. modify the following content in The py file:

TEMPLATE_DIRS = ("C:/Users/xiaowu/workspace/mydjango/templates", # note the slash format, which is/rather than \, even in windows)

7. Create a template file:
In settings. create a template file under the template directory set in The py file. The template files are all html files, but the content contains some special placeholders, which will be replaced in actual applications; these contents are the data implemented in the code, and the template can be inherited, which is also easy to use, as if the code block of the program is the finer and reusable, the better. Example:
Contents of the base.html file under the templatemain directory

      Company Site: {% block title %} Page {% endblock %}{% Block extrahead %} {% endblock %}  {% Block content %} {% endblock %} Content of base.html in template/mytempdirectory [html] view plain copy {% extends "base.html" % }{% block extrahead %}{% Endblock %}

Job_list.html under template/mytempdirectory

{% extends "jobs/base.html" %}  {% block title %}Job List{% endblock %}  {% block content %}   Job List   
 
 
    {% for job in object_list %}
  • {{ job.job_title }}
  • {% endfor %}
{% endblock %}

Job_detail.html under template/mytempdirectory

{% 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. Application Template file:
In django, the template is referenced in views. py. For details, see:
Method 1:

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')[:10]   t = loader.get_template('mytemp/job_list.html')   c = Context({     'object_list': object_list,     })   return HttpResponse(t.render(c)) 

Method 2:

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',                {'object': job}) 

9. The contents of the final views. py file 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')[:10]    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 url of the index and detail views and add the following content in urls. py:

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

Then restart the service and access http: // 127.0.0.1: 8000/job/

Okay, all the structures have been used. The rest is to come up with an interesting project to get started!

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.