Python & Pycharm & Django Build a Web development environment

Source: Internet
Author: User
Tags install django pip install django

First, install the software

1. Install Python 2.7, Pycharm, PIP (Python Package management tool), Django (Pip install Django)


Ii. deployment 1, pycharm after the completion of the new Django project, its directory is as follows: Sub-directory Mydjangoproject represents the global configuration of the project, respectively, setttings.py, urls.py and wsgi.py, Where setttings.py includes the system's database configuration, application configuration, and other configurations, urls.py represents the configuration of the Web project URL mapping. Subdirectory student is an app created under the project that contains the models.py, tests.py and views.py Files templates directory is the template file directory manage.py is a Django provides a management tool, you can synchronize the database and so on 2, after the start of the creation, you can start normally. Click the Run button to start the Times wrong:
1 Traceback (most recent):2File"d:/workspace/mydjangoproject/manage.py", Line 10,inch<module>3 execute_from_command_line (SYS.ARGV)4File"D:\Python27\lib\site-packages\django\core\management\__init__.py", line 338,inchExecute_from_command_line5 Utility.execute ()6File"D:\Python27\lib\site-packages\django\core\management\__init__.py", Line 312,inchExecute7 Django.setup ()8File"D:\Python27\lib\site-packages\django\__init__.py", Line 18,inchSetup9 apps.populate (settings. Installed_apps)TenFile"D:\Python27\lib\site-packages\django\apps\registry.py", line 89,inchPopulate One     "Duplicates:%s"%App_config.label) ADjango.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
1Installed_apps = (2     'Django.contrib.admin',3     'Django.contrib.auth',4     'Django.contrib.contenttypes',5     'django.contrib.sessions',6     'django.contrib.messages',7     'Django.contrib.staticfiles',8     'Django.contrib.admin',9     'Student',Ten)
Comment out one row after (why there is this problem, estimate is a bug), reboot, OK 3, Web Project add page at this time, we have not written a line of code, the program 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 = ' 
To open the url.py file, you need to configure the URL map: url (r ' ^student/', SayHello) when the user enters Http://**/student, the SayHello method is called, and the method is HttpResponse () Returns the page content as a response. Restart the service, Access http://localhost:8000/student/on the views.py page you can return the page to the browser by calling the HttpResponse () class as a response to the element in the form of a string. 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, the file as a template, the following:
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4     <title></title>5 </Head>6 <Body>7     <ul>8 {% for student in students%}9         <Li>Ten id:{{Student.id}}, Name: {{Student.name}},age: {{student.age} } One         </Li> A {% endfor%} -     </ul> - </Body> the </HTML>
Modify the views.py file, add Method Showstudents ()
1 defshowstudents (Request):2List = [{id:1,'name':'Jack'}, {id:2,'name':'Rose'}]3     returnRender_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 settings.py template configuration: ' DIRS ': [base_dir+r ' \templates '], restart Service, Access/HTTP// Localhost:8000/showstudents, appears: So far, 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:
1DATABASES = {2     'default': {3        '  ENGINE': 'django.db.backends.mysql', 4         'NAME':'Student',5         'USER':'Root',6         'PASSWORD':'1234',7         'HOST':'127.0.0.1',8         'PORT':'3306',9         #' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),Ten     } One}
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:
1  from Import Connection 2 cursor = Connection.cursor ()
If you do not have an error, the configuration is correct. Create model, open models.py, define model as follows:
1 class Student (models. Model):2     id = models. Bigintegerfield3     name = models. Charfield (max_length=20, default='a')
Then call manage.py syncdb Normally, after 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 commandthrough the above two steps, it can be normal operationAdd method in views.py: showrealstudents
1 def showrealstudents (Request): 2     List = Student.objects.all ()3     return render_to_response ('  student.html', {'students': List}
urls.py Add Map URL (r ' ^showrealstudents/$ ', showrealstudents) Restart service, open connection: http://localhost:8000/showRealStudents page output is normal. Now, with Django, you can manipulate the database, customize the template, and show the data on the page.

Python & Pycharm & Django Build a Web development environment

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.