使用相关模型中的值在ModelForm上创建新对象

时间:2013-07-20 20:09:30

标签: django django-models django-forms

我有一个ModelForm允许通过CreateView的子类创建新的User对象,我还有一个带有“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分配与当前(而不是新用户)用户在其个人资料中相同的客户端。

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

1 个答案:

答案 0 :(得分:1)

尝试检查是否

self.object.pk 
调用

后,

有你想要的东西

super(UserCreate, self).form_valid(form)

在你的form_valid方法中。