from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.contrib import auth
# Create your views here.
def showall(request):
mynames = ''
for i in User.objects.all():
#myname += str(i) + '
'
mynames += i.username + '
'
return HttpResponse(mynames)
def find(request):
try:
a1 = User.objects.get(username='john')
return HttpResponse('找到john')
except:
a1 = None
return HttpResponse('查無此人')
def add(request):
#要新增一筆:tom
#先判別是否已經存在資料表內
try:
a1 = User.objects.get(username='mike')
except:
a1 = None
#若無,則新增一筆
if a1==None:
a2 = User.objects.create_user('mike','mike@gmail.com','mike963852')
a2.first_name = '麥克'
a2.last_name = '李'
a2.is_staff = True
a2.save()
return redirect('/showall/')
else:
return HttpResponse('mike 已經存在')
def index(request):
return render(request,'index.html',locals())
def login(request):
mylogin = False
if request.method =='POST':
myname = request.POST['myname']
mypw = request.POST['mypw']
#驗證是否是user資料表成員
a1 = auth.authenticate(username=myname,password=mypw)
#判別是否為有效成員,且通過驗證
if a1 is not None:
if a1.is_active:
auth.login(request,a1)
message = '已經成功登入'
return redirect('/index/')
#return render(request,'index.html',locals())
else:
message = '帳號還沒有開始啟用'
else:
message = '沒有這個帳號'
return render(request,'login.html',locals())
#return redirect('/login/')
def logout(request):
auth.logout(request)
#return render(request,'index.html',locals())
return redirect('/index/')