在django-profile中添加字段first_name和last_name

时间:2011-05-22 01:21:11

标签: python django django-models django-forms

我需要添加与之关联的first_namelast_name字段  User模型并将其显示在个人资料form中。

字段:

   >>> user = User.objects.get(pk=1)
   >>> user.first_name
       u'Some'
   >>> user.last_name
       u'User'

我的模型是这样的:

class UserProfile(models.Model):
  user = models.ForeignKey(User, unique=True)
  personal_email = models.EmailField(blank=True)
  address = models.CharField(max_length=140)
  phone_number = models.CharField(max_length=20)

  def __unicode__(self):
      return u'Profile of user: %s' % self.user.username

渲染配置文件表单时,必须显示字段。

first_name:  
last_name: 
personal_email:  
address: 
phone_number:

修改

我决定

#forms.py

class UserProfileForm(forms.ModelForm):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].initial = self.instance.user.first_name
        self.fields['last_name'].initial = self.instance.user.last_name

        self.fields.keyOrder = [
            'first_name',
            'last_name',
            'personal_email',
            'address',
            'phone_number',
            ]


    def save(self, *args, **kwargs):
        super(UserProfileForm, self).save(*args, **kwargs)
        self.instance.user.first_name = self.cleaned_data.get('first_name')   
        self.instance.user.last_name = self.cleaned_data.get('last_name')
        self.instance.user.save()

    class Meta:
        model = UserProfile

#urls.py

     url(r'^profiles/edit/', edit_profile, {'form_class': UserProfileForm},
                                             name='profiles_edit_profile'  ),

并添加#signals.py

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        if created:
            userprofile, new = UserProfile.objects.get_or_create(user=instance)

1 个答案:

答案 0 :(得分:3)

假设您使用的是ModelForm,您可以执行以下操作:

class profileForm(ModelForm):
    first_name = forms.CharField(max_length=30, required=False)
    last_name  = forms.CharField(max_length=30, required=False)
    class Meta:
        model = UserProfile

    def save(self, commit=True):
        m = super(customerForm, self).save(commit=False)
        # Update and save user model here
        if commit:
            m.save()
        return m

您可以跳过覆盖保存方法并在视图中执行保存。只需获取名字和姓氏值,并在验证表单后保存它。您可能还希望使用事务来确保所有内容都保存或没有任何内容。