2024年5月11日 星期六

在pythonanywhere設計Django網站的登入功能加上圖形驗證

上一篇文章:在pythonanywhere設計Django網站的登入功能

1.安裝django-simple-capcha套件


2.新增captchas APP到mysite/mysit/setting.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 4.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-8c5r7ez2#g2j5n@yxeczdyhw6-zwgj_l64=nark$wc_mn+kf*4'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['cmlin.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bootstrap5',
    'myapp',
    'captcha',
]

CAPTCHA_NOISE_FUNCTIONS = (
    #'captcha.helpers.noise_null', #没有樣式
    'captcha.helpers.noise_arcs', #線
    'captcha.helpers.noise_dots', #點
)

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# default static files settings for PythonAnywhere.
# see https://help.pythonanywhere.com/pages/DjangoStaticFiles for more info
MEDIA_ROOT = '/home/cmlin/mysite/media'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/cmlin/mysite'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR/'static',
    ]

2.修改mysite/mysite/urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from myapp.views import index, vegetable, fruit, post1, post2, edit, login, logout, register

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('index/', index),
    path('vegetable/', vegetable),
    path('fruit/', fruit),
    path('post1/', post1),
    path('post2/', post2),
    path('edit/<int:id>/',edit),
    path('edit/<int:id>/<str:mode>', edit), # 由 edit.html 按 送出 鈕
    path('login/', login),
    path('logout/', logout),
    path('register/', register),
    path('captcha/', include('captcha.urls')),
]

3.修改mysite/myapp/froms.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django import forms
from captcha.fields import CaptchaField

class PostForm(forms.Form):
	image = forms.CharField(max_length=20,initial='')
	title = forms.CharField(max_length=20,initial='',required=False)
	subtitle = forms.CharField(max_length=20,initial='',required=False)

class PostForm2(forms.Form):
    username = forms.CharField(max_length=20,initial='')
    pd = forms.CharField(max_length=20,initial='')
    captcha = CaptchaField()

4.修改mysite/myapp/views.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
from django.shortcuts import render, redirect
from myapp.models import vegetableDB
from myapp.forms import PostForm, PostForm2
from django.contrib.auth import authenticate
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse

# Create your views here.
def index(request):
    slide1 = {'image':'fruits01.jpg', 'active':'active', 'interval':'10000', 'title':'水果01', 'subtitle':'好水果在雲林'}
    slide2 = {'image':'fruits02.jpg', 'active':'', 'interval':'2000', 'title':'水果02', 'subtitle':'好水果在雲林'}
    slide3 = {'image':'fruits03.jpg', 'active':'', 'interval':'3000', 'title':'水果03', 'subtitle':'好水果在雲林'}
    slides = [slide1, slide2, slide3]
    if 'login' in request.session:
        login = request.session['login']
    else:
        login = 0
    return render(request, 'index.html', locals())

def vegetable(request):
    vegetables = vegetableDB.objects.all().order_by('id')
    return render(request, 'vegetable.html', locals())

def fruit(request):
    return render(request, 'fruit.html', locals())

def post1(request):
	if request.method == "POST":
		image1 = request.POST['image']
		title1 =  request.POST['title']
		subtitle1 =  request.POST['subtitle']
		#新增一筆記錄
		unit = vegetableDB.objects.create(image=image1, title=title1, subtitle=subtitle1)
		unit.save()
		return redirect('/')
	else:
		message = '請輸入資料(資料不作驗證)'
	return render(request, "post1.html", locals())

def post2(request):  #新增資料,資料必須通過驗證
	if request.method == "POST":  #如果是以POST方式才處理
		postform = PostForm(request.POST)  #建立forms物件
		if postform.is_valid():			#通過forms驗證
			image1 = postform.cleaned_data['image'] #取得表單輸入資料
			title1 =  postform.cleaned_data['title']
			subtitle1 =  postform.cleaned_data['subtitle']
			#新增一筆記錄
			unit = vegetableDB.objects.create(image=image1, title=title1, subtitle=subtitle1)
			unit.save()
			return redirect('/')
		else:
			message = '驗證碼錯誤!'
	else:
		message = 'image, title, subtitle'
		postform = PostForm()
	return render(request, "post2.html", locals())

def edit(request,id=None,mode=None):
	if mode == "edit":  # 由 edit.html 按 submit
		unit = vegetableDB.objects.get(id=id)  #取得要修改的資料記錄
		unit.image=request.GET['image']
		unit.title=request.GET['title']
		unit.subtitle=request.GET['subtitle']
		unit.save()  #寫入資料庫
		return redirect('/vegetable/')
	else: # 由網址列
		try:
			unit = vegetableDB.objects.get(id=id)  #取得要修改的資料記錄
		except:
			message = "此 id不存在!"
		return render(request, "edit.html", locals())

def login(request):
	if request.method == 'POST':
	    postform2 = PostForm2(request.POST)
	    if postform2.is_valid():
	        name = postform2.cleaned_data['username']
	        password = postform2.cleaned_data['pd']
	        user = authenticate(username=name, password=password)
	        if user is not None:
	            if user.is_active:
	                auth.login(request,user)
	                message = '登入成功!'
	                request.session['login']=1
	                return redirect('/index/')
	            else:
	                message = '帳號尚未啟用!'
	                request.session['login']=0
	    else:
	        request.session['login']=0
	        return redirect('/index/')
	else:
		postform2 = PostForm2()
	return render(request, "login.html", locals())

def logout(request):
	auth.logout(request)
	request.session['lgoin']=0
	return redirect('/index/')

def register(request):
	if request.method == 'POST':
		name = request.POST['username']
		first_name = request.POST['first_name']
		last_name = request.POST['last_name']
		password = request.POST['password']
		email = request.POST['email']
		user = authenticate(username=name, password=password)
		try:
		    user=User.objects.get(username=name)
		except:
		    user=None
		if user!=None:
		    message = user.username + " 帳號已建立!<a href='/index/'>Home</a>"
		    return HttpResponse(message)
		else:	# 建立 test 帳號
		    user=User.objects.create_user(name,email,password)
		    user.first_name=first_name
		    user.last_name=last_name
		    user.is_staff=True
		    user.save()
		    return redirect('/index/')
	return render(request, "register.html", locals())

5.修改mysite/templates/login.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<html>
<form action="." method="POST" name="form1">
    {% csrf_token %}
    <div>帳號:{{postform2.username}}</div>
    <div>密碼:{{postform2.pd}}</div>
    <div>驗證碼:{{postform2.captcha}}</div>
    <div>
    <input type="submit" name="button" id="button" value="登入" />
    </div>
    <span style="color:red">{{message}}</span>
</form>
<h2><a href='/register/'>註冊</a></h2>
</html>

6.執行migrate指令

7.執行結果:


沒有留言:

張貼留言