在pycharm中创建一个Django项目
运行一次,或者在终端输入:
python manage.py runserver
启动服务器
创建一个app:test_2,在终端输入
python manage.py startapp test_2
连接数据库,init.py
import pymysql
pymysql.install_as_MySQLdb()
没有的话记得要安装pymysql包
配置路由,在urls.py中
urlpatterns = [
path('admin/', admin.site.urls),
path('test_2/', include('test_2.urls')),
]
修改setting.py,添加APP应用test_2
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'test_2',
]
使用MySQL数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
在终端将数据库映射到数据模型,可以在models.py看到
python manage.py inspectdb > test_2\models.py
记得将文件编码改为 UTF-8 models.py中生成的
class TestTable(models.Model):
test_id = models.IntegerField(primary_key=True)
test_name = models.CharField(max_length=45, blank=True, null=True)
test_pwd = models.CharField(max_length=45, blank=True, null=True)
class Meta:
managed = False
db_table = 'test_table'
在templates中创建html文件 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<label>欢迎来到登录页面</label>
<form action="/test_2/index/" method="post">
{% csrf_token %}
<p><label>用户名:</label><input name="user"></p>
<p><label>密码:</label><input name="pwd"></p>
<input type="submit" value="提交">
</form>
</body>
</html>
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<label>欢迎来到注册页面</label>
<form action="/test_2/register/" method="post">
{% csrf_token %}
<p><label>用户名:</label><input name="user"></p>
<p><label>密码:</label><input name="pwd"></p>
<input type="submit" value="注册">
</form>
</body>
</html>
创建view
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
import random
def toLogin_view(request):
return render(request, 'login.html')
def Login_view(request):
u = request.POST.get("user", '')
p = request.POST.get("pwd", '')
if u and p:
ans = TestTable.objects.filter(test_name=u, test_pwd=p).count()
if ans >= 1:
return HttpResponse("登录成功!")
else:
return HttpResponse("账号密码错误!")
else:
return HttpResponse("请输入正确的账号和密码!")
def toRegister_view(request):
return render(request, 'register.html')
def Register_view(request):
u = request.POST.get("user", '')
p = request.POST.get("pwd", '')
if u and p:
ans = TestTable(test_id=random.choice('3456789'), test_name=u, test_pwd=p)
ans.save()
return HttpResponse("注册成功!")
else:
return HttpResponse("请输入完整的账号和密码!")
配置子路由
from django.urls import path
from . import views
urlpatterns = [
path('', views.toLogin_view),
path('index/', views.Login_view),
path('toregister/', views.toRegister_view),
path('register/', views.Register_view),
]
运行试一下
|