I have a ModelForm to allow the creation of new User objects via a subclass of CreateView, and I also have a UserProfile model with a "client" field, and connected to the User model. This:
# models.py
class UserProfile(TimeStampedModel):
user = models.OneToOneField(User, unique=True)
client = models.ForeignKey(Client)
# forms.py
class UserForm(ModelForm):
def create_userprofile(self, user, client):
profile = UserProfile()
profile.user = user
profile.client = client
profile.save()
class Meta:
model = User
fields = ('email', 'username', 'password', 'first_name', 'last_name', 'groups')
# views.py
class UserCreate(LoginRequiredMixin, CreateView):
model = User
template_name = 'usermanager/user_form.html'
form_class = UserForm
success_url = reverse_lazy('usermanager:list')
def form_valid(self, form):
### Make sure a newly created user has a UserProfile.
# some pseudo-code thrown in
# First save the user
result = super(UserCreate, self).form_valid(form)
# Now that we have a user, let's create the UserProfile
form.create_userprofile(created_user, current_user.userprofile.client)
# Finally return the result of the parent method.
return result
I want to be able to create a new UserProfile when the form is submitted (and is valid, of course), so I was doing it on the CreateView.form_valid() method, but I need the ID of the just created user, which at that time I don't think I have - do I?
At the same time, I need to assign to the new UserProfile the same client as the current (not the new) user has in his profile.
Any thoughts on how to achieve this?