django測試平臺開發,註冊
阿新 • • 發佈:2020-09-21
#1-先建表--建立建立使用者-角色-許可權表
#註冊使用md5加密,可以寫入tools.py
import hashlib
def md5(s):
'''md5'''
m = hashlib.md5(s.encode())
return m.hexdigest()
### models.py ###
class User(BaseModel): name = models.CharField(max_length=200,verbose_name='名字') phone = models.CharField(max_length=11,verbose_name='手機號') password = models.CharField(max_length=200,verbose_name='密碼')
@staticmethod def mack_password(row_password): '''row_password:原始密碼''' tmp_password = '%s%s' %(row_password,SECRET_KEY) md5_password = md5(tmp_password) return md5_password def check_password(self,row_password):return self.mack_password(row_password) == self.password def set_password(self,row_password): self.password = self.mack_password(row_password) def __str__(self): return self.name class Meta: verbose_name = '使用者表' verbose_name_plural = verbose_name db_table= 'user' class Roles(BaseModel): desc = models.CharField(verbose_name='角色描述',max_length=20,unique=True) name = models.CharField(verbose_name='角色標識',max_length=20,unique=True) class Meta: verbose_name = '角色表' verbose_name_plural = verbose_name db_table = 'roles' class Permission(BaseModel): roles = models.ForeignKey(Roles,on_delete=models.DO_NOTHING,db_constraint=False,verbose_name='角色') user = models.ForeignKey(User,on_delete=models.DO_NOTHING,db_constraint=False,verbose_name='使用者') class Meta: verbose_name = '許可權表' verbose_name_plural = verbose_name db_table = 'permission'
#2-先實現註冊介面,註冊請求時先校驗請求引數,使用ModelForm
### forms.py
class RegisterForm(forms.ModelForm): class Meta: model = models.User exclude = {'id','is_delete','update_time','create_time'}
#3-views中寫入介面邏輯
class Register(PostView): model_class = models.User form_class = forms.RegisterForm # 重寫 post 方法進行定製化開發 # 將前端傳遞的 password 進行md5加密 def post(self, requests): # 通過from進行資料驗證 form_obj = self.form(requests.POST) # 資料驗證是否通過 if form_obj.is_valid(): # 建立資料 # form_obj.cleaned_data 是所有驗證通過的資料 data = form_obj.cleaned_data data['password'] = self.model_class.mack_password(data['password']) print('data', data) self.model.objects.create(**data) return NbResponse() else: # 返回錯誤資訊 # return JsonResponse({"code": "500", "msg": form_obj.errors.get_json_data()}) return NbResponse(code=500, msg=form_obj.error_format)
#4-配置urls