Django 定义模型执行迁移

1,创建应用

Test/app8

 python manage.py startapp app8

2,注册应用

Test/Test/settings.py

3,配置路由

Test/Test/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('app8/', include('app8.urls')),
]

4,添加模型

Test/app8/models.py

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=50, unique=True)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128)   
    first_name = models.CharField(max_length=60)
    last_name = models.CharField(max_length=50)
    # 添加其他字段,例如:
    # age = models.IntegerField()
    # bio = models.TextField()
    # ...

    class Meta:
        db_table = 'users2'

    def __str__(self):
        return self.username

5,应用目录下创建urls.py

Test/app7/urls.py

from django.urls import path
from . import views


urlpatterns = [
    
]

6,生成应用迁移文件

python manage.py makemigrations app8

7,执行应用迁移

python manage.py migrate app8

可以看到数据库已经创建了表

8,添加视图函数

Test/app8/views.py

from django.shortcuts import render
from .models import User


def create_user(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        # ... 获取其他字段的值

        # 创建用户实例
        user = User(
            username=username,
            email=email,
            # ... 填充其他字段
        )
        user.save()  # 保存到数据库
        # ... 处理成功或失败的逻辑
    return render(request, '8/1.html')

9,添加应用路由

Test/app8/urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('create_user', views.create_user, name='create_user'),
]

10,添加html代码

Test/templates/8/1.html

<!DOCTYPE html>
<html>
<head>
  <title>创建用户</title>
</head>
<body>
  <form method="POST">
    {% csrf_token %}
    <label for="username">用户名:</label>
    <input type="text" name="username" id="username"><br><br>
    <label for="email">邮箱:</label>
    <input type="email" name="email" id="email"><br><br>
    # ... 添加其他字段的输入框
    <button type="submit">创建用户</button>
  </form>
</body>
</html>

11,访问页面

http://127.0.0.1:8000/app8/create_user

可以看到我们的数据成功存在表里面了

相关推荐
交换喜悲8 分钟前
深度学习之半监督学习:一文梳理目标检测中的半监督学习策略
论文阅读·人工智能·python·学习·目标检测·计算机视觉·目标跟踪
Learning改变世界15 分钟前
Shell代码解读
python·shell
爱看书的小沐28 分钟前
【小沐学AI】Python实现语音识别(faster-whisper-webui)
人工智能·python·ai·nlp·whisper·语音识别·fast-whisper
啊取名真困难1 小时前
TG群发机器人:高效自动化消息分发指南
python·机器人·自动化
疯狂学习GIS1 小时前
核对不同文件夹所含内容的差异并提取缺失内容:Python代码
python·学术工作效率
bryant_meng1 小时前
【python】OpenCV—Feature Detection and Matching
开发语言·python·opencv·特征匹配·特征检测
Ren_xixi2 小时前
如何在pycharm里面运行pytest用例
python·pycharm
⁡ ⁡2 小时前
Python打字练习
python
新手村领路人2 小时前
macos m2 百度paddleocr文字识别 python
开发语言·python·macos