先來建置註冊的部分。
新增Register資料工作表來儲存註冊的帳號及密碼:
class Register(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
用Django提供的Django Form來做一個註冊的表單,首先在mysite/quiz底下新增forms.py,新增內容如下:
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=20, required=True)
password = forms.CharField(max_length=20, required=True)
接著回到views.py:
from .forms import RegisterForm
def register_create_view(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
Register.objects.create(****form.cleaned_data)
form = RegisterForm
context = {
'form':form
}
return render(request, 'register_create.html', context)
要將表格輸出只要寫'form.as_p'即可,'form.as_p'就是把將表單的每個欄位包裹在一個標籤內,像下面這樣:
<p><label for="id_username">username:</label>
<input id="id_username" type="text" name="username" maxlength="20" required></p>
新增register_create.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">送出</button>
</form>
</body>
</html>
*quiz/urls.py*
urlpatterns = [
...
path('register_create', views.register_create_view),
]
小結:其實Django的內建APP auth就有提供上述的功能,model跟form都內建好了,使用auth可以替我們免去這些動作。admin網頁裡面有個Users,就是儲存註冊者的資料。