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

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

相关推荐
IVEN_14 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang16 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮16 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling16 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮19 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽19 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers