經典案例:利用表單(models.Model)寫一個登入註冊小例項
阿新 • • 發佈:2018-12-17
1、models.py檔案: from django.db import models class User(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=16) telephone = models.CharField(max_length=11) 2、forms.py檔案: from django import forms # 注意是django下的forms from one.models import User class RegisterForm(forms.ModelForm): pwd1 = forms.CharField(max_length=16, min_length=6) pwd2 = forms.CharField(max_length=16, min_length=6) # 如果要控制多個欄位,就要重寫clean()函式 def clean(self): cleaned_data = super().clean() pwd1 = cleaned_data.get('pwd1') pwd2 = cleaned_data.get('pwd2') if pwd1 != pwd2: raise forms.ValidationError('兩個密碼不一致!') class Meta: model = User exclude = ['password'] 3、views.py檔案: from django.views.generic import View from one.forms import RegisterForm # 定義GET或者POST方法:根據是GET還是POST請求來做相應的操作 class IndexView(View): # 如果是GET請求,那麼返回一個空的表單 def get(self, request): form = RegisterForm() return render(request, 'one/index.html', {'form': form}) # 如果是POST請求,那麼將提交上來的資料進行校驗 def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): # 在呼叫save方法的時候,如果傳入一個commit=False,那麼只會生成這個模型的物件,而不會把這個物件真正的插入到資料庫中 user = form.save(commit=False) # 通過clean()驗證之後,再將建立的物件真正的插入資料庫中 user.password = form.cleaned_data.get('pwd1') user.save() return HttpResponse("註冊成功") else: return HttpResponse("註冊失敗") 4、路由 path('', IndexView.as_view()) 5、index.html檔案: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> <table> {{ form.as_table }} <tr> <td></td> <td><input type="submit" value="提交"></td> </tr> </table> </form> </body> </html>