1

我有一个 ModelForm 允许通过 CreateView 的子类创建新的用户对象,我还有一个带有“客户端”字段的 UserProfile 模型,并连接到用户模型。这:

# 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 分配与当前(不是新)用户在其个人资料中的相同客户端。

关于如何实现这一目标的任何想法?

4

1 回答 1

1

尝试检查是否

self.object.pk 

打电话后有你想要的

super(UserCreate, self).form_valid(form)

在您的 form_valid 方法中。

于 2013-07-20T20:16:51.947 回答