想通過django的Form模塊進行數據庫中是否已存在用戶名的驗證,首先我先調用了數據庫用戶名字段所有的值,發現是個queryset對象。
隨后經過查詢后發現queryset查詢集對象可以調用list工廠方法后,生成一個類似於[('user_name_1','username_2')]的對象,隨即把列表中的元組對象拿出來進行遍歷,完成驗證,form代碼如下:
class Registerform(forms.Form): user_name = forms.CharField(label='你的姓名', max_length=10,error_messages={ }) user_psd = forms.CharField(label='你的密碼',widget=forms.PasswordInput()) user_psd2 = forms.CharField(label='請再次輸入你的密碼',widget=forms.PasswordInput()) email = forms.EmailField(label='你的郵件地址',widget=forms.TextInput) def clean(self): cleaned_data = self.cleaned_data pwd = self.cleaned_data['user_psd'] pwd2 =self.cleaned_data['user_psd2'] user_form = self.cleaned_data['user_name'] user_model = list(models.User_info.objects.all().values_list('user_name')) for i in user_model:#此步i為類似(username_1,username_2,)的元組對象 print(user_form) if user_form in i: raise forms.ValidationError('用戶名已存在,請重新嘗試登錄') if pwd!=pwd2: raise forms.ValidationError('兩次輸入的密碼不匹配') return cleaned_data