Django 连接数据库并使用(简单案例记录)
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DjangoPro', #自己设置数据库名称
'USER': 'root',
'PASSWORD': '******', #数据库密码
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
models.py:
class Join(models.Model):
username = models.CharField(max_length=25)
password = models.CharField(max_length=25)
输入命令:
python manage.py makemigrations
python manage.py migrate
views.py:
def data(request):
if request.method=='GET':
return render(request, 'homepage.html')
else:
uname = request.POST.get('username', '')
#根据html中 input的 name!
upwd = request.POST.get('password', '')
if uname and upwd:
join_user = Join(username=uname, password=upwd)
join_user.save()
return render(request, '成功')
return HttpResponse('失败')
html:
<form style="background-color:#c7ddef; margin-top:9vh; padding:2vh" method="post" action="">
{% csrf_token %}
<div class="form-group" >
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter username" name="username">
</div>
<table style="width:100%">
<tr>
<td>
<div>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
</div>
</td>
<td>
<button style="float:right" type="submit" id="denglu_sss" class="btn btn-info">Log in</button>
</td>
</tr>
</table>
</form>
打开数据库中相应的表: