I need add the first_name
and last_name
fields associated with
that User
model and display it in the profile form
.
fields:
>>> user = User.objects.get(pk=1)
>>> user.first_name
u'Some'
>>> user.last_name
u'User'
My model is something like this :
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
when rendering the profile form, would have to show the fields.
first_name:
last_name:
personal_email:
address:
phone_number:
Edit
I resolved to:
#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' ),
and add in #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)
To have the extra fields appearing in the admin just: Edit your admin.py and set the form property to refer to the form you created above. Include your new fields in your fields or fieldsets declaration.
If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
Assuming you are using a ModelForm you could do the following:
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
You could skip overriding the save methods and do the save in your view. Just get get the first and last name value and save it after you validate the form. You might also want to used a transaction to make sure everything saves or nothing does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With