Django学习系列之用户注册

在上篇文章的基础上,做些小小的改动.

forms.py

class RegisterForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'id':'pass'}))
    sex = forms.ChoiceField(widget=forms.RadioSelect,choices=SEX_CHOICES)
    birthday = forms.DateField(required=False,widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    phone = forms.CharField(required=False,validators=[validate_phone])

    class Meta:
        model = Register
        #fields = ['nickname','username','password','phone']
        fields = '__all__'

    def clean(self):
        cleaned_data=super(RegisterForm,self).clean()
        nick_name=cleaned_data.get('nickname')
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')
        email = cleaned_data.get('email')
        db_email = Register.objects.filter(email=email)

        .....


       if email in [email.email for email in db_email]:
            self._errors['email'] = self.error_class([u"邮箱已经存在,请换一个!"])
        return cleaned_data

views.py

def register(request):
    sn="TC"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    if request.method == 'POST':
         regform = RegisterForm(request.POST,auto_id="%s",error_class=DivErrorList)
         if regform.is_valid():
             username = regform.cleaned_data['username']
             user=regform.save(commit=False)
             user.sn = sn
             user.save()
             return HttpResponseRedirect("/success/%s/" %username)
    else:
         regform = RegisterForm(auto_id="%s",label_suffix=":") #auto_id有3种设置:True/False/str 若是False不需要html元素中的id标识与True相反,auto_id="%s",则是field的名字
    return render(request,"register.html",{'reg':regform})

def success(request,name):
    return render(request,"sucess.html",{'username':name})


呵呵,成功将记录写到数据库中了。

改天,再写个用户登录(会话要考略了)。

你可能感兴趣的:(django,save,ModelForm)