Preparation: When django project, app application created: 1: In the settings in the app INSTALLED_APPS list of application names configured 2: Create a static folder, used to store css, js, img and other static files 3: File after the establishment of static folder, you need to perform configuration file settings in STATICFILES_DIRS = [ os.path.join (base_dir, 'static') ] # exposed to the outside world can still access the server folder below all the resources here to add: STATIC_URL = '/ xxx /' # Interface name prefixed with the static folder does not matter, consistent with the default static folder path: STATICFILES_DIRS = [ os.path.join (base_dir, 'static'), # is your static folder path os .path.join (base_dir, 'static1'), os.path.join (base_dir, 'static2') ] # PS: find all will turn static file paths found in the list, then stop immediately, did not find returns a 404 4: All html files in the default templates folder resource way to introduce external html page: cdn introduced The files in the local file in the project folder under static 5: Form trigger action form to submit data to the back end of two ways <the INPUT of the type = "the Submit"> <the Button> </ the Button> 6: submission form address data Specifies the action attribute is used to control the address submitted by: full path: <action = "http://127.0.0.1:8000/login/" form> only write path suffix: <form action = "/ Login /"> did not write (default submission to the current path) form the default form is get request
GET and POST are two basic methods of the HTTP request GET difference is most intuitive to the parameters included in the URL, POST body passes parameters request. 'Standard answer': Dot 9 1 Shi .GET fallback in the browser is harmless, and POST will submit the request again. 2 ... GET the URL of address can be generated Bookmark, and not POST. 3 ... GET request will be actively cache browser, POST will not, unless manually. 4 ... GET request can only be url encoded, and POST supports multiple encoding. 5 ... GET request parameters will be retained in full in the browser history, and the POST parameters will not be retained. . 6 ... GET request transmitted in the URL parameters are limited length, but it has POST. 7 For argument's data type, GET accepts only ASCII characters, but there is no limit POST. . 8 ... GET less secure than POST, because the parameters directly exposed on the URL, it can not be used to transmit sensitive information. 9.GET parameters passed via the URL, POST Request body in place.
Depending on the mode of execution client requests different logic code DEF Login (Request): # acquisition request submitted by the client mode print (request.method) # request method to get the whole string to uppercase if request.method == 'GET': return the render (Request, 'login.html') elif request.method == 'POST': return HttpResponse ( "received a brother") # personal advice in accordance with the following written in this way reduce code redundancy and confusion structure problems DEF Login (Request): IF request.method == 'the POST': return the HttpResponse ( 'the OK') return the render (Request, 'the login.html') function should return a string defined data type, attention necessary to achieve by HttpResponse, this time not to tangle the other two methods because the inside thereof and associated HttpResponse
Dot landing encountered: DEF the Login (Request): # client acquisition request submitted by way of print (request.method) # request method to get the string GET ALL CAPS or POST IF request.method == ' the pOST ': Print (of request.POST) # as you put it inside a large dictionary to store all the data submitted by the client post # request.POST: <QueryDict: {' username ': [' jason '],' password ': [' 123 ']}> Print (request.POST.get (' username ')) # value acquired though a list, but it is to get the value of the single element when the # default value will take the last element of the list inside request.POST:<QueryDict #: { 'username': [ 'Jason', 'Egon'], 'password': [ '123']}> Print (request.POST.getlist ( 'username')) # To Get a list of one-time value of all data which requires a GetList () Print (of request.POST [ 'password']) # Deprecated data acquisition method, to acquire by GET return the render (Request, 'the login.html') Get value inside a list of all the elements need to use getlist scenarios: the user's preferences, the checkbox get only get to the last element value list
django to connect to the database: 1, to find the right PyCharm Databases, click into the fill data 2, a database connection is established, you need to modify the configuration file DATABASES = { 'default': { 'ENGINE': 'django.db.backends. MySQL ', ' NAME ':' Michael ', ' the HOST ':' 127.0.0.1 ', ' PORT ': 3306, ' the USER ':' the root ', ' PASSWORD ':' 123 ' } } PS: keys must both uppercase 3, after modifying the configuration file, replace the default pycharm connect to the database module mode 1: in your project folder below __init__.py mode 2: you can also use folders in your __init__.py following fixed wording: pymysql Import pymysql.install_as_MySQLdb () # tell django with pymysql connect to the database instead of mysqldb
The django orm: Review: orm definition: object-relational mapping class "" "Table " "Objects" table record attribute "target", "the value of a field in a corresponding record django orm is not automatically help you create a library, but It can automatically help you create a table, as follows: from django.db Import Models # the create your Models here Wallpaper. class the User (models.Model): the above mentioned id = models.AutoField (primary_key = True) name = models.CharField (max_length = 32) password models.CharField = (MAX_LENGTH = 32) DEF __str __ (Self): return the self.name # __str__ described above is used when printing an object by means of which the interior of the control class, the printer default name attribute. Of course, you can change to a different attribute name. When the database connection is established, you need to use the database migration (synchronous) command python3 manage.py makemigrations your database changes on a small notebook to record (and will not help you create a table) python3 manage.py the migrate your database changes synchronized to the database # After operation, the system will automatically add a prefix, to avoid the same table names appear between the plurality app
CRUD dots process encountered: 1. New data # insert data operation database user table # mode. 1: USER_OBJ = models.User.objects.create (name = username, password = password) # mode 2: USER_OBJ = models.User (name = username, password = password) user_obj.save () # call the save method to save objects to the database create and save effect # here like that to save the current data in query data user_list = models.User. objects.all () # Get the user table all of the data print (user_list) # <QuerySet [ <user: user object>, <user: user object>, <user: user object>]> is obtained QuerySet object # can be obtained by internal class definition __str__ method, when the object to be printed, to obtain a name attribute # QuerySet long as it can obtain the current point of view the query object's internal QuerySet sql statement print (user_list.query) using a tag href attribute specifies the path of the page jump href can write the whole path but it is recommended to write the suffix <a href="/reg/" class="btn btn-success">Adding data </a> Redirect redirect can write someone else's web site can be your path to return redirect ( '/ UserList') return redirect ( '/ UserList /') # recommend this writing, avoid redirection value queryset object: the index value (not recommended) .first value method (recommended) to use .query: the type to use only by queryset 3. delete models.User.objects.filter (id = 1) .delete ( ) All data will queryset # Remove all objects # here filter used to filter out all of the data qualifying note when the data is queryset query data or data types, the normal value of the data type is recommended under the following methods: USER_QUERY = models.User. objects.filter (ID = edit_id) .first () ID herein by band parameter after url, a GET request with the value query data in two ways: filter # recommended data does not exist, an empty return get # when this property does not exist, an error 4, edit obtain edit object id by: embodiment 1: using a hidden input type = hidden tag which can, at the same time to bring the value returned <input type = "hidden" name = "edit_id" value = "{{user_obj.pk}}"> way: When the assignment to the action parameter in the form tape form <form action = "/ edit / edit_id = {? {user_obj.pk}} "method =" post "> edit: mode. 1: models.User.objects.filter (ID = edit_id) .Update (name = username, password = password) embodiment 2: Get the current data object user_obj models.User.objects.filter = (ID = edit_id) .first () user_obj.name = username user_obj.save ()
When the tables in the model layer and associated data has been modified, it must perform database migration command again python manage.py makemigrations recorded on the books of small python manage.py migrate real operational database