从用户获取输入到Django的个人资料模型中

时间:2018-10-17 14:57:24

标签: python django django-models django-forms django-views

我有一个注册表单,它是UserCreationForm的扩展名,并且我有一个UserProfileForm。我在用户注册期间将两种形式都呈现为相同html

问题是,输入已保存到内置用户模型中,但没有保存到概要文件模型中。配置文件模型中没有显示数据。

我已经尝试了很多方法,并寻找了许多解决方案,但是找不到错误。

我的forms.py看起来像这样-

class RegistrationForm(UserCreationForm):

      email = forms.EmailField(required=True)
      first_name = forms.CharField(required=True)
      last_name = forms.CharField(required=True)
      username = forms.CharField(required=True)

      class Meta:
         model = User
         fields = ['username',
                  'first_name',
                   'last_name',
                   'email',
                   'password1',
                   'password2'
                  ]

       def save(self,commit):
            user = super(RegistrationForm,self).save(commit=False)

       if commit:
           user.save()

       return user


class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        exclude = ['user']

    def save(self,commit):
         user = super(RegistrationForm,self).save(commit=False)
         USN =self.cleaned_data['USN']
         year = self.cleaned_data['year'] 
         sem = super(RegistrationForm,self).save(commit=False)

         if commit:
            user.save()

         return user

已在models.py中创建了UserProfile模型

class UserProfile(models.Model):

    alphanumeric = RegexValidator(r'^[0-9A-Z]*$', 'Only alphanumeric 
                                  characters are allowed.')
    user = models.OneToOneField(User, related_name = 
                                'profile',on_delete=models.CASCADE)
    USN = models.CharField(max_length=50, blank=True, null=True, validators= 
                          [alphanumeric])
    year = models.IntegerField(default=0)
    sem = models.IntegerField(default=0)

    def __str__(self):
         return self.user.username

 def create_profile(sender, **kwargs):
   if kwargs['created']:
       objects=models.Manager()
       user_profile = UserProfile.objects.create(user=kwargs['instance'])
 post_save.connect(create_profile, sender = User)

我已经使用了Views.py中的两种形式-

def register(request):
if request.method == 'POST':
    form_1 = RegistrationForm(request.POST)
    form_2 = UserProfileForm(request.POST)
    if form_1.is_valid() and form_2.is_valid():
        save_1 = form_1.save(commit = False)
        save_2 = form_1.save(commit = False)
        save_1.save()
        save_2.save()
        return render(request,'main/home.html')
else:
    form_1 = RegistrationForm()
    form_2 = UserProfileForm()
args = {'form_1':form_1,'form_2':form_2}
return render(request, 'account/register.html',args)

个人档案模型对象中的用户名显示正确,但是其他字段未更新。我希望其他字段也在配置文件对象中得到更新。

0 个答案:

没有答案