实现注册功能
——与spqlit数据库连接
- 创建一个应用stu_2,实现一个登陆功能
python manage.py startapp stu_2
- 在test_2/urls.py的urlpatterns列表添加:
urlpatterns = [
path('admin/', admin.site.urls),
path('student/',include('stu.urls')),
path('register/',include('stu_2.urls')) #增加register/,完成注册功能
]
- 在stu_2/urls.py中添加(指向views中定义的函数):
#coding='utf-8'
from django.urls import path
from . import views
urlpatterns=[
path('',views.index_view)
]
- 在stu_2/views.py中添加:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index_view(request):
m = request.method
if m == "GET":
return render(request,'register.html')
else:
return HttpResponse("处理注册功能")
- 在stu_2/models.py中添加:
from django.db import models
# Create your models here.
class Student(models.Model):
sname = models.CharField(max_length=30,unique=True)
spwd = models.CharField(max_length=30)
#class Meta:
# db_table = 't_stu'
-
在pycharm右侧的datebase,点击“+”
-
修改views.py文件和models.py
# views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import *
# Create your views here.
def index_view(request):
m = request.method
# 获取当前请求方法
if m == "GET":
return render(request,'register.html')
else:
# 获取请求参数
uname = request.POST.get('uname','')
pwd = request.POST.get('pwd','')
#判断
if uname and pwd:
# 创建模型对象
stu_2 = Student(sname=uname,spwd=pwd)
# 插入数据库
stu_2.save()
return HttpResponse('注册成功')
return HttpResponse("注册失败")
models.py
from django.db import models
# Create your models here.
class Student(models.Model):
sname = models.CharField(max_length=30,unique=True)
spwd = models.CharField(max_length=30)
#class Meta:
# db_table = 't_stu'