Django-based database operation methods (detailed description) and django operation methods

Source: Internet
Author: User

Django-based database operation methods (detailed description) and django operation methods

Django claims to be "the most suitable perfect WEB framework for development with a deadline ". This article uses the Django web Development Guide to quickly build a blog that involves many knowledge points. It will not be detailed here. If you are the first to contact Django, this article will give you a perceptual understanding of Django. After completing this article, you will be interested in reading related books and documents.

Unless otherwise stated, the following environments will be used in the future:

==============================

Windows 7/10

Python 1, 3.5

Django 1, 1.10

==============================

1: Create a project

Create a mysite project:

E:/WWWROOT/python/> django-admin.py startproject mysite

Of course, the premise is that you have set the python environment variable!

For the IDE tool (PyCharm4.0 is used in this article), create a Project in File> New Project> Django.

After creation, the project directory structure is as follows:

Manage. py ----- A tool in the Django project that can call django shell and database.

Settings. py ---- contains the default settings of the project, including database information, debugging flag, and other working variables.

Urls. py ----- maps the URL mode to the application.

2. Create a blog Application

In python, it is called app.

E:\WWWROOT\python\mysite>python manage.py startapp blog

A blog folder is generated in the project.

3: Database Operations

Initialize the database:

Python comes with SQLite database. Django supports various mainstream databases. Here we use SQLite first. If you use other databases, set them in the settings. py file. The default database configuration is as follows:

DATABASES = {  'default': {    'ENGINE': 'django.db.backends.sqlite3',    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  }}

Use the default data configuration to initialize the database:

E:\WWWROOT\python\mysite>python manage.py migrate

After the command is executed, some data tables are generated:

Django comes with a WEB Background. the user name and password for the WEB Background are created below:

E:\WWWROOT\python\mysite>python manage.py createsuperuserSystem check identified some issues: WARNINGS:?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the followingsettings into your default TEMPLATES dict: TEMPLATE_DIRS.Username (leave blank to use 'administrator'): rootEmail address: admin@admin.comPassword:Password (again):Superuser created successfully.

Next, use the account and password created above to log on to the background. To log on to the background, you must add the created APP or blog in the settings. py file:

INSTALLED_APPS = [  'django.contrib.admin',  'django.contrib.auth',  'django.contrib.contenttypes',  'django.contrib.sessions',  'django.contrib.messages',  'django.contrib.staticfiles',  'blog',]

Note that a comma must be followed!

Start the django container:

E:\WWWROOT\python\mysite>python manage.py runserver

The default WEB address is http: // 127.0.0.1 and port is 8000. Use this address and port to access the Home Page:

Go to the django Background: http: // 127.0.0.1/admin

Use the user and password created above to log on to the background!

If you want to connect to the mysql database instead of using SQLite, you must first install the pymysql module. python3.5 does not support the MySQLdb module! After the installation is complete, follow these steps:

First, configure the database in the settings. py file:

DATABASES = {  'default': {    'ENGINE': 'django.db.backends.mysql',    'HOST': '127.0.0.1',    'PORT': 3306,    'NAME': 'djangodb',    'USER': 'root',    'PASSWORD': 'root',  }}

Create a djangodb database in mysql DATA and add the following code to the mysite/_ init _. py file:

import pymysqlpymysql.install_as_MySQLdb()

Run the following command line:

E:\WWWROOT\python\mysite>python manage.py makemigrationsE:\WWWROOT\python\mysite>python manage.py migrate

In this way, the data table is initialized in the mysql database:

For demonstration, I changed the database link to SQLite.

Create a UseInfo table and create fields:

Now we open the models. py file under the blog directory, which is where we define the blog data structure. Open the mysite/blog/models. py file and modify it:

from django.db import models # Create your models here.class UserInfo(models.Model):  username = models.CharField(max_length=32)  password = models.CharField(max_length=32)  age = models.IntegerField()

Command Line execution:

E:\WWWROOT\python\mysite>python manage.py makemigrationsE:\WWWROOT\python\mysite>python manage.py migrate

A data table is created in the database:

It can be seen that Django uses the APP name as the data table prefix by default and the class name as the data table name!

The created fields are as follows:

As you can see, Django adds an id field by default. This field is the primary key and automatically increases.

Add data in the blog_UserInfo table:

Django creates data by importing the models. py file in the views. py file:

From django. shortcuts import render # Create your views here. from blog import models # import blog module from django. shortcuts import HttpResponsedef db_handle (request): models. userInfo. objects. create (username = 'andy ', password = '000000', age = 33) return HttpResponse (' OK ')

Next we configure the route so that the browser can access the views. py file:

from django.conf.urls import urlfrom django.contrib import admin from blog import viewsurlpatterns = [  url(r'^admin/', admin.site.urls),  url(r'^db_handle', views.db_handle),]

Next we will access http: // 127.0.0.1/db_handle

Check whether the database is successfully created:

The preceding figure shows how to create table data. You can also create table data in dictionary format:

def db_handle(request):  # models.UserInfo.objects.create(username='andy',password='123456',age=33)  dic = {"username":"bruce","password":"123456","age":23}  models.UserInfo.objects.create(**dic)  return HttpResponse('OK')

Through the above method, we create several more data records, as shown in:

Delete table data:

The views. py file is as follows:

from django.shortcuts import render # Create your views here.from blog import modelsfrom django.shortcuts import HttpResponsedef db_handle(request):  # models.UserInfo.objects.create(username='andy',password='123456',age=33)  # dic = {"username":"bruce","password":"123456","age":23}  # models.UserInfo.objects.create(**dic)  models.UserInfo.objects.filter(id=2).delete()  return HttpResponse('OK')

The operation method is the same as above. Execute it again in the browser, and the data with id = 2 in the data will be deleted:

Modify Table data:

From django. shortcuts import render # Create your views here. from blog import modelsfrom django. shortcuts import HttpResponsedef db_handle (request): models. userInfo. objects. filter (id = 1 ). update (age = 18) # Find the data with id = 1 and change age to 18 return HttpResponse ('OK ')

Data Query:

To display the queried data more intuitively, we will use the Django template function to display the queried data in a WEB browser.

Create a new t1.html file in the templatesdirectory. The content is as follows:

<! DOCTYPE html> 

Query data in the views. py file and specify the called template file. The content is as follows:

from django.shortcuts import render# Create your views here.from blog import modelsfrom django.shortcuts import HttpResponsedef db_handle(request):  user_list_obj = models.UserInfo.objects.all()  return render(request,'t1.html',{'li':user_list_obj})

Note:Failed template error. In order to find the template file under mysite/templates, we also need to configure the template path in the settings. py file:

TEMPLATES = [{'backend': 'django. template. backends. django. djangoTemplates ', 'dirs': [OS. path. join (BASE_DIR, 'templates')], # configure the template path 'app _ dirs': True, 'options': {'Context _ processors ': ['django. template. context_processors.debug', 'django. template. context_processors.request ', 'django. contrib. auth. context_processors.auth ', 'django. contrib. messages. context_processors.messages ',] ,},},]

You can view the following information in the browser:

Introduce static files such as JS and CSS:

Create a static directory under the mysite directory and store all JS and CSS files in this directory! And specify the static directory in the settings. py file:

 STATIC_URL = '/static/' STATICFILES_DIRS = (   os.path.join(BASE_DIR,'static'), )

Form submission data:

To submit a form using post in Django, You Need To comment out the following line in the settings. py configuration file:

# 'django.middleware.csrf.CsrfViewMiddleware',

Submit a ticket (t1.html is still used here ):

<! DOCTYPE html> 

Write to database (views. py ):

from django.shortcuts import render# Create your views here.from blog import modelsfrom django.shortcuts import HttpResponsedef db_handle(request):  if request.method == "POST":    models.UserInfo.objects.create(username=request.POST['username'],password=request.POST['password'],age=request.POST['age'])  user_list_obj = models.UserInfo.objects.all()  return render(request, 't1.html', {'li': user_list_obj})

After data is submitted, for example:

Django Execution Process

The above django-based database operation method (detailed description) is all the content shared by the editor. I hope to give you a reference, and I hope you can provide more support to the customer center.

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.