【问题标题】:Can't update User and UserProfile in one View?无法在一个视图中更新用户和用户配置文件?
【发布时间】:2016-07-14 18:53:50
【问题描述】:

我使用UpdateView 来更新用户帐户。用户由 User 和 UserProfile 组成,如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile')
    telephone = models.CharField(max_length=40,null=True)

现在,我创建了一个类UpdateView 以便能够更新例如UserProfile - 电话有效。

表格:

class UserProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('telephone',)

网址:

url(r'^edit-profile$',view=views.UserUpdate.as_view(),name='user_update'),

查看:

# @login_required
class UserUpdate(UpdateView):
    form_class = UserProfileUpdateForm
    context_object_name = 'user_update'
    template_name = 'auth/profiles/edit-profile.html'
    success_url = 'success url'

    def get_object(self,queryset=None):
        return self.request.user.userprofile

    def form_valid(self, form):
        #save cleaned post data
        clean = form.cleaned_data
        self.object = form.save()
        return super(UserUpdate, self).form_valid(form)

现在,我希望能够更改一些属于 User 的属性和一些属于 UserProfile 的属性。

我已经尝试更改 UserProfileUpdateForm 字段变量,但它根本不起作用...

class UserProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('telephone','model.user.first_name',) <- this does not work, I want to add to the form attribute 'first_name' which belongs to User, not UserProfile

您知道如何使用UpdateView 更改电话、名字、姓氏等吗?

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:

    UpdateView 仅用于处理一个没有关系的模型。然而,美妙的django-extra-views 库为模型和内联关系提供了 CBV。

    class UserProfileInline(InlineFormSet):
        model = models.UserProfile
        form = UserProfileUpdateForm
        extra = 0
        def get_factory_kwargs(self):
            kwargs = super(UserProfileInline,self).get_factory_kwargs()
            kwargs.update({"min_num": 1})
            return kwargs
    
    class UserCreate(CreateWithInlinesView):
        model=User
        inlines = [UserProfileInline]
        form_class = UserForm
        success_url = reverse('some-success-url')
        # REQUIRED - fields or exclude fields of User model
        template_name = 'your_app/user_profile_update.html'
    

    请务必查看documentation,了解有关传递给模板的变量以及如何使用inline formsets 的信息。

    【讨论】:

      【解决方案2】:

      您还必须为User 创建第二个表单。然后将其传递给相同的UpdateView 作为第二个form_class。

      注意*:您可能需要覆盖 UpdateView 的 get 和 post 方法。 This SO answer 可能会有所帮助。

      在一个模板中在一个&lt;form&gt; 标签下呈现两种表单:

      <form action="" method="post">
          {% csrf_token %}
          {{ first_form }}
          {{ second_form }}
      </form>
      

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 2021-08-01
        • 1970-01-01
        • 2022-01-07
        • 2017-05-19
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多