Python full stack web framework Django Basic operation

Source: Internet
Author: User
Tags install django

Django Operations Summary!django Framework installation: CMD installation: PIP3 install Django Pycharm installation: Search for Django installations under Python variables
Create a Django project: Create a Django project under cmd: Create a Django Program: Django-admin startproject mysite into the program directory: CD MySite
Start the socket server, wait for the user to send the request IP Port python manage.py runserver 127.0.0.1:8080
Create a Django project under Pycharm: simply create a new Django project! Startup program: Run Django directly, and a fixed IP and port URL address will be generated after startup. Port default: 8000;ip Default: 127.0.0.1. The browser accesses this URL directly, with hints that the creation was successful.
Pycharm the Django operation:
I. Configuration files:-under Project:-Create static files for Css,js, images, etc.-Create a view function file for writing view functions-Create a SQL database connection file Create a connection to the database by using the class to reduce code reuse. -Add or see the correct path in Settings:-template path: Template_dirs = (Os.path.join (base_dir, ' templates '),)-Static file path: Staticfiles_dirs = (OS.P Ath.join (Base_dir, ' static '),)-Hidden middleware path in ' Django.middleware.csrf.CsrfViewMiddleware ' Information II, routing system: routing relationship: URL---& Gt    function in the urls.py file to import the view function file, write on the road by the relationship! Example: from the App01 import views url (R ' ^login/', views.login), the routing system in Django differs from other language frameworks, and in Django each requested URL has a route map,     This allows the request to be handled by a function in the view.  Most other web frameworks are a route map for a class of URL requests, which makes the routing system concise. Third, the view function: After determining the corresponding routing relationship, you need to write a routing function. All the information is obtained from the database, it is necessary to establish a link to the database in the function, get the data!      Pymysql operation, Skip!     Note:-When defining a function, you must set the request to receive the browser from the parameter request! -How to determine the request: Request.method-Get data submitted in a non-pass way: (get mode, post mode)--->
Get the information submitted in the request header URL, on the page URL can be seen!
The Post method submits the information in the request body. cannot be viewed directly!
Request. Get.get () Gets a value submitted by the Get method request. Post.get () Gets the Post method submitted by a value request. Post.getlist () Gets the array information submitted by post (multi-valued)
-Return information: (three ways) return HttpResponse (' string ') returns string return redirect (' URL ') jump to a URL page under return render (Request, ' template path (. htm L file) jump to a template page return render (request, ' template path ', {value}) jumps to a template page and returns a value to this page. Render essence: 1. Get template + data, background rendering; 2. Httpreponse (...) Return the rendered string information to the page
            Add: Template rendering is performed in the background, and then the string is returned to the stencil, through the browser rendering display! Value type: The pass value must be in dictionary form! Multiple values can be passed! Key is a string, value can be a single value, a list, a dictionary! {' K1 ': ' v1 ', single value type ' K2 ': [1,2,32,34], List type ' K3 ': {' x1 ': ' V2 ' ...}, dictionary type} Four, Template: Template rendering: For the function to pass back the value, the template is through the value of the key to get!!!      This must be noticed!    Template language: (Note: For lists or dictionaries, getting the elements in them is a.!!!)    The concept of the front end does not have an index to go to the value, but the front-end support point method to get it.   For example a dictionary dic = {"K1": v1} ====> dic.k1 get value v1) gets a single value: {{K1}} Gets a value from the list: {{K2. Index value}} gets all single values: Loop mode: {% for item in K3%}{{ITEM.K1}}  ...... {% ENDFOR%} If conditional: {% if condition%} statement {% Else%} statement {% endif%} template operation mode: 1, new URL method: Click to jump to another URL page-note: To jump to the new URLs path must be written in this way- ----> "/urls path/".      Otherwise the background is not recognized address will be error! Whether it's a form form or a label! Note the way to write the path of the URLs of the jump or submit information!  2, Modal box operation: Click on the trigger event, a bullet box appears! -Front-end JS Application Note: HTTP connection, built on top of the TCP connection!  The HTTP protocol has: stateless, short connection features!  The rendering of the template engine, which is performed on the server, is a protocol that provides a communication interface, in essence, the socket redirection is the operation of the browser Wsgi! Five, ajaxhtml, there is a click to jump, the page refresh function of the label is: a tag, or form form!  If you don't want the page to refresh automatically but the person is in control, then you need Ajax.  Actions to block events: 1. Write the event type in the tag, write return in the function, and write return false in the function; -<a onclick= ' return func (); ' ></a> func () {... return false}2, by way of jquery object, bind tagTo set an event, write the return false in the event trigger function directly-<a id= "a" ></a> $ ("#a)." Click (function () {... .... return false})
Ajax is a method of jquery, you need to import the jquery file before use!   Note: page data must be a string type regardless of whether it is submitted or received. Data value type: string, or array, no dictionary format! If you want to pass the JSON into a string first! JSON syntax for the page: Json.stringify (object)----> String Json.parse ("string")----> Object ajax Syntax: $.ajax ({URL: ' Address to commit ', type: ' PO ST ',//Get or post, submission method data: {' K1 ': ' v1 ', ' K2 ': ' V2 '},//Data submitted DataType: ' JSON ',//Set the data type received traditional:true,//if the value of the submitted data has a column table, you need to add this property success:function (data) {///successful, execute callback function location.href = "Address to jump" location.reload ()//page reload//After the current server finishes processing, Auto-Execute callback function//data returned}) for the use of Ajax, the view function has also made some changes, with a stored state dictionary, with error detection!  The returned result must also be a string type of information! Example of a View function code: DEF change_class (request): ret = {"Status": True, "message": None} try:cid = Request. Post.get ("cid") CNAME = Request. Post.get ("CNAME") sql = "Update class set cname =%s WHERE cid =%s" Sqlmodus.put (Sql,[cname,cid,])
Except Exception as e:ret["status"] = falseret["message"] = "Handling Exception" return HttpResponse ((ret))//using JSON to convert objects to String return template
Modal and new URLs application scenario analysis:
Modal dialog box (Ajax) for:-Few input boxes-less Data example: Login
New URL mode-operation multi-for a large number of data and how the operation of the specific application or need to depend on the specific circumstances and requirements of the operation! No, absolutely!
  HTTP request lifecycle: request header, fetch URL----function (template + data rendering), return User (response header + response body) VI: Motherboard operations: Django Master: Master: Store all pages Common sub-board: Inherit Master-        Customize the current page private things according to normal operation to generate a master Board page, in the head tag to write two block blocks as a flag bit, for importing CSS and JS file under the body tag to write a block block as a flag bit, for importing different code master:

 

Python full stack web framework Django Basic operation

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.