2024年5月1日 星期三

在pythonanywhere設計Django網站的登入功能

延續文章:在pythonanywhere設計Django網站的卡片(Card)功能(新增For Template)

1.修改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
"""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 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),
]

2.修改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
from django.shortcuts import render, redirect
from myapp.models import vegetableDB
from myapp.forms import PostForm
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':
		name = request.POST['username']
		password = request.POST['password']
		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:
			message = '登入失敗!'
			request.session['login']=0
			return redirect('/index/')
	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())

3.修改templates/index.html

 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
<!DOCTYPE html>
<html>
<head>
  {% load bootstrap5 %}
  {% bootstrap_css %}
  {% bootstrap_javascript %}
  {% load static %}
</head>
<body>
<div id="carouselExampleInterval" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-inner">
    {% for item in slides %}:
        <div class="carousel-item {{ item.active }}" data-bs-interval= {{ item.interval }}>
            <img src="{% static 'images/' %}{{ item.image }}" class="d-block w-100" alt="...">
            <div class="carousel-caption d-none d-md-block">
                <h5 style="color:white;">{{ item.title }}</h5>
                <p style="color:white;">{{ item.subtitle }}</p>
            </div>
        </div>
    {% endfor %}
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

<div class="container">
  <ul class="nav bg-info">
    <li class="nav-item">
      <a class="nav-link link-light" href="/">首頁</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/vegetable/">蔬菜</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/fruit/">水果</a>
    </li>
    <li class="nav-item">
      {% if login  == 1 %}
        <a class="nav-link link-light" href="/logout/">登出</a>
      {% else %}
        <a class="nav-link link-light" href="/login/">登人</a>
      {% endif %}
    </li>
  </ul>
<h1>虎科小農超市</h1>

<p>虎科大是一所很重視永續發展暨社會責任的大學</p>
  {% block content %}
  {% endblock %}
</div>

</body>
</html>

4.新增 login.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<html>
<form action="." method="POST" name="form1">
    {% csrf_token %}
    <div>帳號:<input type="text" name="username" id="username"/></div>
    <div>密碼:<input type="password" name="password" id="password"/></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>

5.新增register.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<html>
<form action="." method="POST" name="form1">
    {% csrf_token %}
    <div>帳號:<input type="text" name="username" id="username"/></div>
    <div>密碼:<input type="password" name="password" id="password"/></div>
    <div>姓氏:<input type="text" name="last_name" id="last_name"/></div>
    <div>名字:<input type="text" name="first_name" id="first_name"/></div>
    <div>Email:<input type="text" name="email" id="email"/></div>
    <div>
    <input type="submit" name="button" id="button" value="註冊" />
    </div>
    <span style="color:red">{{message}}</span>
</form>
</html>


沒有留言:

張貼留言