将数据保存到数据库的问题

时间:2015-11-01 14:55:41

标签: django django-forms django-views

这是我的views.py

      def signup(request):
            print "signup"
            if request.method == 'POST':
                print "post signup"
                form = RegisterForm(request.POST)
                try:
                    if form.is_valid():
                        print form.cleaned_data
                        u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )
                        ui = UserInfo()
                        ui.user = u
                        ui.class_of = form.cleaned_data['gradyear']
                        ui.grade = form.cleaned_data['grade']
                        ui.balance = 0

                        ui.save()

在我的forms.py中我有:

 class RegisterForm(forms.Form):
        GRADE_CHOICES = ( 
                    (9,'9'), (10,'10'), (11,'11'), (12,'12') , 
                )
        curr_year = date.today().year
        GRAD_YEAR_CHOICES = ( 
                    (curr_year,curr_year), (curr_year+1,curr_year+1), (curr_year+2,curr_year+2), (curr_year+3,curr_year+3) , 
                     )
        first_name = forms.CharField(max_length = 25)
        last_name = forms.CharField( max_length = 25)
        emailid = forms.EmailField()
        passwd1 = forms.CharField(max_length=100,widget=forms.PasswordInput)
        passwd2 = forms.CharField(max_length=100,widget=forms.PasswordInput)
        gradyear = forms.ChoiceField( choices=GRAD_YEAR_CHOICES)
        grade = forms.ChoiceField( choices=GRADE_CHOICES)

        def clean(self):
            cleaned_data = super(RegisterForm, self).clean()

            if cleaned_data['passwd1'] != cleaned_data['passwd2']:
                raise forms.ValidationError({'passwd1':['Password do not match']})

            if User.objects.filter(email=cleaned_data['emailid']).count():
                raise forms.ValidationError({'emailid':['Email already taken ']})

            return cleaned_data

除了first_name和last_name之外,为什么所有内容都打印到数据库? (用户名,电子邮件,成绩,年级和密码全部保存)

编辑:这是我的UserInfo

 class UserInfo(models.Model):
    user = models.OneToOneField(User, related_name='user_infos')
    class_of = models.IntegerField()
    #username = user.username
    #fname = user.fname
    #lname = user.last_name
    #email = user.email
    #Staff = user.is_staff
    pub_date = models.DateTimeField( auto_now=True)
    grade = models.IntegerField()
    balance = models.DecimalField(max_digits=6, decimal_places=2)
    #first_name = models.CharField(max_length = 25)

1 个答案:

答案 0 :(得分:1)

在提供的代码中,您永远不会为first_namelast_name保存UserUserInfo

def signup(request):之后,就在这一行之后:

u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )

尝试包含此内容:

u.first_name = form.cleaned_data['first_name']
u.last_name = form.cleaned_data['last_name']
u.save()