Django+mysql configuration and simple operation database example code

Django+mysql configuration and simple operation database example code

Step 1: Download the mysql driver

cmd enters the created Django project directory: use the command

pip install mysqlclient

Wait for the installation to succeed!

Step 2: Configure MySQL connection parameters in settings.py (install MySQL first if there is no MySQL)

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'Database name (you need to create a database in MySQL first)',
    'USER':'mysql user name (such as root)',
    'PASSWORD': 'Password (such as 123456789)',
    'HOST':'Domain name (127.0.0.1 or localhost)',
    'PORT':'Port number (3306)',
  }
}

Step 3: Create a model class in models.py

from django.db import models
# Create your models here. Similar to the Model in the MVC architecture
class Article(models.Model):
  title = models.CharField(max_length=60,default='title')
  content = models.TextField(null=True)

Step 4: Create a database table based on the model class

1. Enter the Django project path using cmd

2. Python manage.py migrate #Create table structure, other tables of non-model class, required by Django

3. python manage.py makemigrations app name #Prepare for data migration

For example: python manage.py makemigrations myblog myblog is the name of the app in my project

4. python manage.py migrate # Execute migration and create medel table structure

Step 5: Start writing code

First of all, let's talk about the requirement, which is to insert a record into MySQL in the code and display it on the page

1. Create a new template under templates, which is actually a page, such as index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h2> {{article.title}}</h2>
Content: {{ article.content }}
</body>
</html>

Use {{ }} to display data on the page. You will understand it after looking at it here.

2. Configure URL

1. Configure the URL mapping in urls.py under the project (note that it is urls.py under the project):

from django.conf.urls import url,include
from django.contrib import admin
#Root url configuration urlpatterns = [
  #url(page regular expression, response method name)
  url(r'^admin/', admin.site.urls),
  url(r'^myblog/',include('myblog.urls')),
]

Note that there is an include('myblog.urls') which is the secondary url we will configure next, configured in urls.py under app

from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
  #url(page regular expression, response method name) ^index$: indicates that the page starts and ends with index, regular expression constraint url(r'^index/$',views.index),
]

Now an access path of 'localhost:8000/myblog/index/' is configured. url(r'^index/$',views.index) means that the path /myblog/index/ is responded by the index method in views.py.

3. Write a response function: such as inserting a data into the data and displaying it on the page

from django.shortcuts import render
from django.http import HttpResponse
from myblog.models import Article
# Create your views here.
def index(request):
  article = Article(title='Title', content='Content!')
  article.save()
  return render(request,'index.html',{'article':article}

Step 6: Run the project

I use pycharm here, just click the run button, if you don’t have pycharm, you can use:

python manage.py runserver

Start the server, then enter http://localhost:8000/myblog/index/ in your browser, and you’re done!

The above is the Django+MySQL configuration and simple database operation example code introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!

You may also be interested in:
  • Detailed explanation of Django connecting to MySQL database and creating table operations
  • How to connect Django 2.2 to MySQL database
  • Complete steps for configuring MySQL database in Django
  • Detailed explanation of how to use Pycharm to connect to MySQL database in Django
  • Django uses the existing data table method of Mysql database
  • Django1.7+python 2.78+pycharm configuration mysql database tutorial
  • Django framework configuration mysql database implementation process

<<:  Simple analysis of EffectList in React

>>:  Specific use of GNU Parallel

Recommend

React new version life cycle hook function and usage detailed explanation

Compared with the old life cycle Three hooks are ...

How to query whether the mysql table is locked

Specific method: (Recommended tutorial: MySQL dat...

Detailed explanation of small state management based on React Hooks

Table of contents Implementing state sharing base...

Mac VMware Fusion CentOS7 configuration static IP tutorial diagram

Table of contents Install CentOS7 Configuring Sta...

Detailed steps to install JDK and Tomcat in Linux environment

Table of contents 1. Install JDK Manual Installat...

Significantly optimize the size of PNG images with CSS mask (recommended)

This article is welcome to be shared and aggregat...

Simple Implementation of HTML to Create Personal Resume

Resume Code: XML/HTML CodeCopy content to clipboa...

Detailed explanation of FTP environment configuration solution (vsftpd)

1. Install vsftpd component Installation command:...

HTML embed tag usage and attributes detailed explanation

1. Basic grammar Copy code The code is as follows...

Detailed installation instructions for the cloud server pagoda panel

Table of contents 0x01. Install the Pagoda Panel ...

JavaScript implements the pot-beating game of Gray Wolf

1. Project Documents 2. Use HTML and CSS for page...

Detailed explanation of docker network bidirectional connection

View Docker Network docker network ls [root@maste...

MySQL query example explanation through instantiated object parameters

This article will introduce how to query data in ...