form_valid创建新记录而不是在form_valid中更新

时间:2014-07-30 12:00:24

标签: django django-views

我有以下代码,我想从updateView更新另一个表。我正在使用以下代码但是在方法 - form_valid中它最终创建新记录而不更新正在编辑的记录。

form.instance = form.save(commit=False)
super(AssetInfoUpdateView, self).form_valid(form)

我正在使用get_context_data方法添加我可以在form_valid中使用的上下文数据来更新"其他表"。

有人能指出我如何更新form_valid中的当前记录或我做错了什么?我已经在views.py中包含了相关的代码 - 因为它在Create中的类似方法很有效,但我似乎无法弄清楚如何让Update工作。

class AssetInfoUpdateView(LoginRequiredMixin, UpdateView):
    model = AssetInfo
    context_object_name = 'asset_info'
    success_url = '/asset/list/'
    template_name = 'asset_mgmt/assetinfo_update.html'
    form_class = AssetInfoUpdateForm
    def get_context_data(self, **kwargs):
        context = super(AssetInfoUpdateView, self).get_context_data(**kwargs)
        alarm_dispatch_current = AlarmDispatchInfo.objects.filter(asset=self.object)
        alarm_dispatch = AlarmNotificationReceiverInfo.objects.all()
        context['alarm_dispatch_current'] = alarm_dispatch_current
        context['alarm_dispatch'] = alarm_dispatch
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(AssetInfoUpdateView, self).get(request, *args, **kwargs)

    def get_object(self, queryset=None):
        obj = AssetInfo.objects.get(pk=self.kwargs['pk'])
        return obj

    def form_valid(self, form,request):
        clean = form.cleaned_data
        form.instance = form.save(commit=False)
        super(AssetInfoUpdateView, self).form_valid(form)
        ....
        ...

    def post(self, request, *args, **kwargs):
        form = AssetInfoUpdateForm(request.POST)
        if( form.is_valid() ):
            return self.form_valid(form,request)
        else:
             return self.form_invalid(form)

0 个答案:

没有答案