逻辑
# 登录 def login(request): err_msg = ‘‘ if request.method == ‘POST‘: username = request.POST.get(‘username‘) password = request.POST.get(‘password‘) obj = auth.authenticate(request, username=username, password=password) if obj: auth.login(request, obj) return redirect(reverse(‘my_customer‘)) err_msg = ‘用户名或密码错误‘ return render(request, ‘login.html‘, {‘err_msg‘: err_msg}) # 注册 def reg(request): form_obj = RegForm() if request.method == ‘POST‘: form_obj = RegForm(request.POST) if form_obj.is_valid(): # 创建新用户 # 方法一 # form_obj.cleaned_data.pop(‘re_password‘) # models.UserProfile.objects.create_user(**form_obj.cleaned_data) # 方法二 obj = form_obj.save() obj.set_password(obj.password) obj.save() return redirect(‘/login/‘) return render(request, ‘reg.html‘, {‘form_obj‘: form_obj})
表单处理
# 注册form class RegForm(forms.ModelForm): password = forms.CharField( label=‘密码‘, widget=forms.widgets.PasswordInput(), min_length=6, error_messages={‘min_length‘: ‘最小长度为6‘} ) re_password = forms.CharField( label=‘确认密码‘, widget=forms.widgets.PasswordInput() ) class Meta: model = models.UserProfile # fields = ‘__all__‘ # 所有字段 fields = [‘username‘, ‘password‘, ‘re_password‘, ‘name‘, ‘department‘] # 指定字段 # exclude = [‘‘] widgets = { ‘username‘: forms.widgets.EmailInput(attrs={‘class‘: ‘form-control‘}), ‘password‘: forms.widgets.PasswordInput, } labels = { ‘username‘: ‘用户名‘, ‘password‘: ‘密码‘, ‘name‘: ‘姓名‘, ‘department‘: ‘部门‘, } error_messages = { ‘password‘: { ‘required‘: ‘密码不能为空‘, } } def clean(self): pwd = self.cleaned_data.get(‘password‘) re_pwd = self.cleaned_data.get(‘re_password‘) if pwd == re_pwd: return self.cleaned_data self.add_error(‘re_password‘, ‘两次密码不一致‘) raise ValidationError(‘两次密码不一致‘)
原文地址:https://www.cnblogs.com/niuli1987/p/9857821.html
时间: 2024-10-09 01:01:04