Django学习(实现登录功能)

1.登录功能

1).在test项目中,修改配置文件setting.py 此时连接mysql数据库

DATABASES = {
    'default': {
       # 'ENGINE': 'django.db.backends.sqlite3',
       #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
       'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pro202',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '123456'
    }
}

2).数据的模型类

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Student(models.Model):
    sname = models.CharField(max_length=30)
    spwd = models.CharField(max_length=30)
    def __unicode__(self):
        return r'Student:%s%s'%(self.sname,self.spwd)
    

3).生成数据库表

#创建当前应用的迁移文件
python manage.py makemigrations stu

#生成数据库表
python manage.py migrate

4).配置url

#test\urls
from
django.conf.urls import url, include from django.contrib import admin import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^student/',include('stu.urls')) ]
#stu\urls
#
coding=utf-8 from django.conf.urls import url import views urlpatterns=[ url(r'^login/$',views.login) ]

5).配置视图函数

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    else:
        uname = request.POST.get("uname","")
        pwd = request.POST.get("pwd","")
        if uname and pwd:
            c = Student.objects.filter(sname=uname,spwd=pwd).count()
            if c == 1:
                return HttpResponse('登录成功')
        return HttpResponse('登录失败')

6).处理登录功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/student/login/" method="post">
        {% csrf_token %}
        <p>
            <label>用户名:<input type="text" name="uname"></label>
        </p>

        <p>
            <label >密&emsp;码:<input type="password" name="pwd"></label>
        </p>

        <p>
            <lable><input type="submit" value="登录"></lable>
        </p>


    </form>

</body>
</html>

7).访问127.0.0.1:8000/student/login/

posted @ 2019-03-06 16:05  卍卐  阅读(328)  评论(0编辑  收藏  举报