Configuration documentary about deploying the Python Django framework with PyCharm

Source: Internet
Author: User
Tags install django pip install django
This article describes how to use PyCharm to deploy the Django framework of Python. PyCharm is a powerful Python IDE. For more information, see Install software
Install Python 2.7, PyCharm, pip (Python package management tool), and Django (pip install Django)

Deployment
PyCharm new Django Project

The directory is as follows:

The subdirectory MyDjangoProject indicates the global configuration of the project, which is setttings. py, urls. py and wsgi. py, where setttings. py includes the system database configuration, application configuration, and other configurations, urls. py
Indicates the Url ing configuration of the web project.
The subdirectory student is an app created in this project, including models. py, tests. py, views. py, and other files.
The templates directory is the template file directory.
Manage. py is a management tool provided by Django that can synchronize databases and so on.

Start
After the creation is complete, it can be started properly. Click the Run button and an error is reported during startup:

Traceback (most recent call last): File "D:/workspace/MyDjangoProject/manage.py", line 10, 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 89, in populate  "duplicates: %s" % app_config.label)django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin
 

The admin configuration is conflicted. Open the setttings. py file and the admin configuration is repeated.

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

Comment out one of the rows (why is this problem? It is probably a bug), restart, OK

Web Project addition page

At this time, we have not yet written a line of code, and the program will run duang! Add a Hello World page.

Open the student/views. py file and enter the following content:

def sayHello(request):  s = 'Hello World!'  current_time = datetime.datetime.now()  html = ' %s 

%s

' % (s, current_time) return HttpResponse(html)

To open the url. py file, configure url ing:

url(r'^student/', sayHello)

When you enter http: // **/student, the sayHello method is called. This method uses HttpResponse () to return the page content as a response.

Restart the service and access http: // localhost: 8000/student/

On the views. py page, you can call the HttpResponse () Class in the form of a string to return the elements required by the page to the browser as a response. In this way, the page logic is mixed with the page, and handwriting is cumbersome and the workload is large. What should we do if we need to display some dynamic data while the page remains unchanged?
For example, when a user accesses http: // localhost: 8000/student/, we want to dynamically display some student data. You can do this:
First, create the student.html file under the templates directory. The file is used as the template and the content is as follows:

    
 
 
    {% For student in students %}
  • Id: {student. id}, name: {student. name}, age: {student. age }}
  • {% Endfor %}

Modify the views. py file and add the showStudents () method ()

def showStudents(request):  list = [{id: 1, 'name': 'Jack'}, {id: 2, 'name': 'Rose'}]  return render_to_response('student.html',{'students': list})

The token binds list_to_response.txt to student.html on the template page.

Add url ing, url (R' ^ showStudents/$ ', showStudents)
Modify the settings. py template configuration: 'dirs': [BASE_DIR + R' \ templates'],

Restart the service and access http: // localhost: 8000/showStudents. the following error occurs:

Now, we can bind some "dynamic" data to the template. But how to access the database?
Obtain the required data from the database and display it on the page?

First, you need to install the database driver, that is, mysql_python,
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, check whether the database configuration is correct. Run the manage. py shell command to enter the shell interaction interface:
Input:

from django.db import connectioncursor = connection.cursor()


If no error is reported, the configuration is correct.
Create a model, open models. py, and define the model as follows:

class Student(models.Model)  id = models.BigIntegerField  name = models.CharField(max_length=20, default='a')


Then call manage. py syncdb
Normally, after this step is completed, the model will maintain consistency with the database. However, in the test, the table is not created in the database after the command is successfully executed.
In this case, perform the following operations:
(1) comment out the models. py file code and execute manage. py makemigerations student.
[And manage. py migerate -- fake]
(2) Open the comment and run the [manage. py makemigerations student and] manage. py migerate commands
The above two steps can be used properly.

Add method in views. py: showRealStudents

def showRealStudents(request):  list = Student.objects.all()  return render_to_response('student.html', {'students': list})

Urls. py add url ing url (R' ^ showRealStudents/$ ', showRealStudents)

Restart the service and open the connection: http: // localhost: 8000/showRealStudents
The page output is normal.
So far, with Django, you can operate databases, customize templates, and display data on the page.

Server
Because Django comes with a lightweight server, this server is used by default, but this is not allowed in actual production. Apache Httpd Server and mod_wsgi.so are usually used as backend servers in the production environment.

The following deployment environments are: Python2.7.6
1. Install httpd-2.2.25-win32-x86-no_ssl.msi
2. Place the downloaded mod_wsgi.so in the d: \ Program Files \ Apache Software Foundation \ Apache2.2 \ modules module.
3. Create a django. wsgi file under the MyDjangoProject directory of the newly created web project.
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 httpd. conf and 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 normal.
During deployment, an exception occurs as follows:
The translation infrastructure cannot be initialized before the apps registry is ready
The reason is that django. wsgi was written in the old way at the beginning, and changed to the new version.

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.