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).处理登录功能


"en">

    "UTF-8">
    Title


    
"/student/login/" method="post"> {% csrf_token %}

"submit" value="登录">

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

Django学习(实现登录功能)_第1张图片

转载于:https://www.cnblogs.com/sise/p/10483863.html

你可能感兴趣的:(Django学习(实现登录功能))