Reputation: 5066
Django newbie here stumbling my way around the docs. I'm trying to create a user profile using Django's "UserProfiles", but I'm having a little trouble with figuring out the proper way to set the code based on Django docs.
Here's my code, based on the docs. (The create_user_profile is 100% from the docs).
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length = 100)
website = models.CharField(max_length=50)
description = models.CharField(max_length=255)
fullName = models.CharField(max_length=50)
email = models.EmailField(max_length = 100, blank = False)
created = models.DateTimeField(auto_now_add=True)
private = models.BooleanField()
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
What's the -proper- way to set and save these fields?
For example, if I have both the User and UserProfile models in one form (in a registration form, for example), how would I first create, then update all of this, before finally saving?
Upvotes: 1
Views: 369
Reputation: 21002
how would I first create, then update all of this, before finally saving
These aren't separate steps. When you create or update a record in Django, you are saving it to the database.
For the registration form, I'd recommend you set it up as a ModelForm
on User
records, then specify the additional fields you want to save to the profile and save them separately in the save function, like so...
class RegistrationForm(forms.ModelForm):
location = forms.CharField(max_length=100)
# etc -- enter all the forms from UserProfile here
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', and other fields in User ]
def save(self, *args, **kwargs):
user = super(RegistrationForm, self).save(*args, **kwargs)
profile = UserProfile()
profile.user = user
profile.location = self.cleaned_data['location']
# and so on with the remaining fields
profile.save()
return profile
Upvotes: 2
Reputation: 6499
You could call profile.user.save() and after it profile.save() when you need to save data from registration form.
Upvotes: 0