Configuration of the Django framework for deploying Python with Pycharm

Source: Internet
Author: User
Tags install django pip install django
Installing the Software
Install Python 2.7, Pycharm, PIP (Python Package management tool), Django (Pip install Django)

Deployment
Pycharm New Django Project

When finished, its directory is as follows:

Sub-directory Mydjangoproject represents the global configuration of the project, setttings.py, urls.py, and wsgi.py, where setttings.py includes the system's database configuration, application configuration, and other configuration, and urls.py
Represents the configuration of a Web project URL mapping.
Subdirectory student is an app created under the project that contains files such as models.py, tests.py, and views.py.
Templates directory is a directory of template files
Manage.py is a management tool provided by Django, which synchronizes databases and so on

Start
Once the creation is complete, it will start normally. Click the Run button to start the Times wrong:

Traceback (most recent call last): File "d:/workspace/mydjangoproject/manage.py", line ten, in 
 
  
   
    execute_from _command_line (SYS.ARGV) File "D:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in Execute_from_command_line  Utility.execute () File "D:\Python27\lib\site-packages\django\core\management\__ init__.py ", line 312, in execute  django.setup () File" D:\Python27\lib\site-packages\django\__init__.py ", line 18, In Setup  apps.populate (settings. Installed_apps) File "D:\Python27\lib\site-packages\django\apps\registry.py", line populate  "duplicates:%" S "% App_config.label) django.core.exceptions.ImproperlyConfigured:Application labels aren ' t unique, duplicates:admin
 
  

Should be the admin configuration conflict, open the setttings.py file, found that the admin configuration is duplicated

Installed_apps = (  ' django.contrib.admin ',  ' Django.contrib.auth ',  ' django.contrib.contenttypes ',  ' django.contrib.sessions ',  ' django.contrib.messages ',  ' django.contrib.staticfiles ',  ' Django.contrib.admin ',  ' student ',)

After commenting out one of the lines (why there is this problem, estimated to be a bug), reboot, OK

Web Project Add page

At this time, we have not written a line of code, the program is Duang run up! Add a Hello World page now.

Open a. student/views.py file, enter the following

def SayHello (Request):  s = ' Hello world! '  Current_time = Datetime.datetime.now ()  html = '

'% (S, current_time) return HttpResponse (HTML)

To open the url.py file, you need to configure the URL mapping:

URL (r ' ^student/', SayHello)

When the user enters Http://**/student, the SayHello method is called, which returns the page content as a response through HttpResponse ().

Restart Service, Access http://localhost:8000/student/

On the views.py page, you can call the HttpResponse () class as a response to the browser by calling the elements of the page to be in string form. But in this way, page logic and pages mixed together, handwriting is cumbersome, the workload is relatively large. What if we need to show some dynamic data, and the page basically doesn't change?
For example, when users visit http://localhost:8000/student/, we want to show some students ' data on the fly. You can do this:
First, in the Templates directory, create a new student.html file as a template with the following content:

    
 
  
  
    {% for student in students%}
  • id:{{Student.id}}, Name: {{Student.name}},age: {{student.age}}
  • {% ENDFOR%}

Modify the views.py file, add Method Showstudents ()

def showstudents (Request):  list = [{id:1, ' name ': ' Jack '}, {id:2, ' name ': ' Rose '}]  return Render_to_response (' Student.html ', {' Students ': list}

This method binds the list to the template page student.html by using the Render_to_response method as the dynamic data.

Add URL map, url (r ' ^showstudents/$ ', showstudents)
Modify the settings.py template configuration: ' DIRS ': [base_dir+r ' \templates '],

Restart Service, Access http://localhost:8000/showStudents, appear:

At this point, we have been able to properly bind some "dynamic" data to the template. But how do you access the database?
Get the data you need from the database and show it on the page?

First you need to install the database driver, namely Mysql_python,
Then configure the database connection:

DATABASES = {'  default ': '    ENGINE ': ' Django.db.backends.mysql ',    ' NAME ': ' Student ',    ' USER ': ' Root ',    ' PASSWORD ': ' 1234 ',    ' HOST ': ' 127.0.0.1 ',    ' PORT ': ' 3306 ',    # ' NAME ': Os.path.join (Base_dir, ' Db.sqlite3 '),  }}

After the configuration is complete, you need to check that the database configuration is correct and use the manage.py shell command to enter the shell interface:
Input:

From django.db Import connectioncursor = Connection.cursor ()


If you do not have an error, the configuration is correct.
Create model, open models.py, define model as follows:

Class Student (models. Model)  id = models. Bigintegerfield  name = models. Charfield (max_length=20, default= ' a ')


Then call manage.py syncdb
Normally, when this step is done, the model will be consistent with the database. However, in the test, when the command was executed successfully, it was discovered that the database did not establish the table.
For this situation, do the following to normal:
(1) Comment out models.py file code, execute manage.py makemigerations student
"and manage.py migerate--fake"
(2) Open comment, execute "manage.py makemigerations student and" manage.py migerate command
Through the above two steps, it can be normal operation

Add method in views.py: showrealstudents

def showrealstudents (Request):  list = Student.objects.all ()  return render_to_response (' student.html ', {' Students ': list})

urls.py Add Map URL (r ' ^showrealstudents/$ ', showrealstudents)

Restart Service, open connection: http://localhost:8000/showRealStudents
The page output is normal.
Now, with Django, you can manipulate the database, customize the template, and show the data on the page.

Server
Because Django comes with a lightweight server, it is used by default, but is not allowed in real production, and is typically used in production environments with the Apache HTTPD server combined with mod_wsgi.so for back-end servers.

The following deployment environments are: Python2.7.6
1, installation Httpd-2.2.25-win32-x86-no_ssl.msi
2, the download good mod_wsgi.so placed in D:\Program files\apache software foundation\apache2.2\modules module.
3. Create a new Django.wsgi file in the new Web project Mydjangoproject directory
The content is as follows (the corresponding directory needs to be modified):

Import osimport sys djangopath = "D:/python27/lib/site-packages/django/bin" If Djangopath not in Sys.path:  Sys.path.append (djangopath) ProjectPath = ' D:/workspace/mydjangoproject ' if ProjectPath not in Sys.path:  Sys.path.append (projectpath) AppPath = ' D:/workspace/mydjangoproject/mydjangoproject ' if AppPath not in Sys.path:  Sys.path.append (AppPath) os.environ[' django_settings_module ']= ' mydjangoproject.settings ' from Django.core.wsgi Import get_wsgi_applicationapplication = Get_wsgi_application ()

4, modify the httpd.conf, add the following:

LoadModule wsgi_module modules/mod_wsgi.sowsgiscriptalias/"D:/workspace/mydjangoproject/django.wsgi"
 
  
   
    Options followsymlinks  allowoverride None  Order deny,allow
 
   allow from all

OK, restart the server, the page is OK.
During the deployment process, an exception was encountered, as follows:
The translation infrastructure cannot be initialized before the apps registry are ready
The reason is that django.wsgi at the beginning according to the older wording, the new version of the wording is OK.

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