一、思路
注册成功用户数据写入数据库
models相关
1.数据库中是否存在相关的表
2.创建模型类models类,需要继承与models.Model
3.创建对应字段
4.创建迁移文件python manage.py makemigrations stu
5.根据迁移文件生成数据库内容python manage.py migrate
views相关
1.编写注册方法
2.创建数据库对象
3.将页面获取的数据写入到数据库中
二、注册功能实现
1.创建项目及应用,并修改配置文件settings.py

2.项目中添加注册路径

3.应用中添加需要匹配的应用路径,并调用相关视图
# coding=utf-8
from django.conf.urls import url, include
from stu import views
urlpatterns = [
url(r"^$", views.index_view),
# url(r"^register/",include('stu.urls'))
]
4.register.html编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/register/" method="post">
{% csrf_token %}
<p>
<label>用户名:</label><input type="text" name="uname"/>
</p>
<p>
<label>密 码:</label><input type="password" name="pwd"/>
</p>
<p>
<input type="submit" value="登录"/>
</p>
</form>
</body>
</html>
5.model模型创建models.py
from django.db import models
# Create your models here.
# 定义模型类,需要继承于models.Model
class Student(models.Model):
sname = models.CharField(max_length=30, unique=True)
spwd = models.CharField(max_length=30)
# class Meta:
# db_table="t_stu" #应用名_模型名,小写
6.创建views.py视图函数
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from stu.models import Student
def index_view(request):
m = request.method
if m == "GET":
return render(request, 'register.html')
else:
uname = request.POST.get("uname", "")
upwd = request.POST.get("pwd", "")
if uname and upwd:
stu = Student(sname=uname, spwd=upwd)
stu.save()
return HttpResponse("注册成功")
return HttpResponse("注册失败")
7.将自己编写的模型映射到数据库,stu应用名称
第一步:生成迁移文件至stu
python manage.py makemigrations stu
第二步:根据迁移文件映射到表中
python manage.py migrate

8.实现效果

?9.重启服务,测试

三、社区版本pycharm无database解决

?
?
|