Django 提交 form 表单(使用

2023-01-31 00:01:30 django 提交 表单

优化 提交 fORM 表单,https://www.cnblogs.com/klvchen/p/10608143.html
创建数据库的字段,在 models.py 中添加

from Django.db import models

# Create your models here.

class UserInfo(models.Model):
    username = models.CharField(max_length=64)
    sex = models.CharField(max_length=64)
    email = models.CharField(max_length=64)

修改 settings.py 文件

# 在 INSTALLED_APPS 中添加
   'blog',

初始化数据库

# 使用命令行进入项目下
# 生成同步数据库的脚本:
python manage.py makemigrations  

#同步数据库:  
Python manage.py migrate   

修改 urls.py 文件

from djanGo.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('userInfo', views.userInfo),
]

修改 views.py 文件

from django.shortcuts import render
import datetime
from blog import models
# Create your views here.

def userInfo(req):

    if req.method=="POST":
        u = req.POST.get("username", None)
        s = req.POST.get("sex", None)
        e = req.POST.get("email", None)

        models.UserInfo.objects.create(
            username = u,
            sex = s,
            email = e,
        )
    user_list = models.UserInfo.objects.all()

    return render(req, "index.html", {"user_list":user_list})

启动 WEB 服务

python manage.py runserver 8888

浏览器访问 Http://127.0.0.1:8888/userInfo

相关文章