django mysql 表单_Python Django 表单提交数据到mysql并展示
首先1: 新建項目userproject, 新建應用childName
2: 這是childName文件目錄,templates文件夾放insert.html 與 show.html
3: insert.html 與 show.html
/**insert.html**/
用戶登錄1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Title信息展示
{% for line in people_list %}
{{line.username}}{{line.password}}{% endfor %}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
4: Setting配置等
找到INSTALLED_APPS,添加應用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'childName' //添加
]1
2
3
4
5
6
7
8
9
找到MIDDLEWARE
注釋 ‘django.middleware.csrf.CsrfViewMiddleware’
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]1
2
3
4
5
6
7
8
9
數據庫配置
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'monitorprogram',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306'
}
}1
2
3
4
5
6
7
8
9
10
11
12
5: childName/views.py
from childName.models import message
from django.shortcuts import render
# Create your views here.
def insert(request):
if request.method == "POST":
message2 = message()
message2.username = request.POST.get("username")
message2.password = request.POST.get("password")
message2.save()
return render(request,'insert.html')
def list(request):
# message3 = message()
people_list = message.objects.all()
return render(request,"showuser.html",{"people_list": people_list})1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
6: 添加路徑,userproject/urls.py
from django.contrib import admin
from django.urls import include,path
from childName import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show/',views.list), //添加
path('insert/',views.insert) //添加
]1
2
3
4
5
6
7
8
9
7: 數據模型
from django.db import models
# Create your models here.
class message(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=15)1
2
3
4
5
6
8: 執行遷移
數據模型有了,需要映射到數據庫中,并實現指定表的創建
Django中數據模型和數據庫的操作稱為 遷移
在項目根目錄下執行下面兩行命令
python3 manage.py makemigrations
python3 manage.py migrate
執行成功后就會在數據庫中創建相應的表
9:運行項目
python3 manage.py runserver
輸入0987654321 1234點擊提交,
查看mysql多出了這條記錄
顯示
ok!
總結
以上是生活随笔為你收集整理的django mysql 表单_Python Django 表单提交数据到mysql并展示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java $p_javap -c命令详解
- 下一篇: mysql构建栋_【转载】这次拆库 应是