gpt4 book ai didi

python - Django UpdateView 创建新对象

转载 作者:行者123 更新时间:2023-11-30 22:48:56 28 4
gpt4 key购买 nike

我的问题:UpdateView 创建新对象而不是更新以前的对象,我认为它发生是因为在我的 View 的类定义中我重写了 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)

最佳答案

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', {}))

关于python - Django UpdateView 创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976361/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com