Django UpdateView创建新对象

时间:2016-10-11 11:35:13

标签: python django django-class-based-views

我的问题: UpdateView创建新对象而不是更新之前的版本,我认为它的发生是因为在我的视图的类定义中我覆盖了get_object方法,如下所示:

def get_object(self, queryset=None):
    try:
        object_get = self.model.objects.get(pk=self.kwargs['pk'])
    except ObjectDoesNotExist:
        raise Http404("No object found matching this query")

    if self.request.user.is_authenticated():
        if object_get.owner == self.request.user:
            return object_get

因此,如果当前用户不是该对象的所有者 - 此方法不返回任何内容 - 它是我想要的,但我的表单类改为创建新对象:

class ClientCreation(forms.ModelForm):

    class Meta:
        model = Client
        fields = ('name', 'loyal')

我认为这是因为表单没有收到self.instance而是创建新的 - 我应该在这种情况下做什么?我不想要创建新对象,以防对象的所有者不是当前用户我想要什么都没发生然后发送这样的发布请求。我该如何正确实现这个?

更新views.py:

class Distinct(generic.UpdateView):
    def get_object(self, queryset=None):
        try:
            object_get = self.model.objects.get(pk=self.kwargs['pk'])
        except ObjectDoesNotExist:
            raise Http404("No object found matching this query")

        if self.request.user.is_authenticated():
            if object_get.owner == self.request.user:
                return object_get

    def get_form_kwargs(self):
        kwargs = super(Distinct, self).get_form_kwargs()
        if self.request.user.is_authenticated():
            kwargs.update({'user': self.request.user})
        return kwargs

    def post(self, request, *args, **kwargs):
        if request.POST.get('action', '') == 'Delete':
            object_get = self.get_object()
            request.session['deleted_data'] = str(object_get)
            object_get.delete()
            return redirect(reverse('crm:main'))
        else:
            return super(Distinct, self).post(request, *args, **kwargs)

    def get_success_url(self):
        return reverse('crm:{}'.format(self.distinct_template), kwargs={'pk': self.kwargs['pk']})

class DistinctClient(Distinct):

    form_class = ClientCreation
    model = Client
    template_name = 'crm/client_detail.html'
    all_template = 'clients'
    distinct_template = 'client'

    def get_form_kwargs(self):

        return generic.UpdateView.get_form_kwargs(self)

1 个答案:

答案 0 :(得分:3)

UpdateView中,如果get_object返回None,django将创建一个新对象。而不是返回None做任何你想做的事。

def get_object(self, queryset=None):
    try:
        object_get = self.model.objects.get(pk=self.kwargs['pk'])
    except ObjectDoesNotExist:
        raise Http404("No object found matching this query")

    if self.request.user.is_authenticated():
        if object_get.owner == self.request.user:
            return object_get
    raise My #do something here.

<强>更新

class My(Exception):
    pass
class DistinctClient(Distinct):

    form_class = ClientCreation
    model = Client
    template_name = 'crm/client_detail.html'
    all_template = 'clients'
    distinct_template = 'client'

    def dispatch(self, *args, **kwargs):
        try:
            return super(DistinctClient, self).dispatch(*args, **kwargs)
        except My:
            return redirect #to do or (return render(self.request, 'mytemplate.html', {}))