CreateView のサブクラスを介して新しい User オブジェクトを作成できるようにする ModelForm があり、「client」フィールドを持つ UserProfile モデルもあり、User モデルに接続されています。これ:
# 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
フォームが送信されたときに (もちろん有効です)、新しい UserProfile を作成できるようにしたいので、CreateView.form_valid() メソッドで作成しましたが、作成したばかりのユーザーの ID が必要です。その時、私は持っていないと思います - そうですか?
同時に、現在の (新規ではない) ユーザーがプロファイルに持っているのと同じクライアントを新しい UserProfile に割り当てる必要があります。
これを達成する方法について何か考えはありますか?