gpt4 book ai didi

python - 将旧的基于函数的通用 CRUD View 转换为新样式的基于类的通用 CRUD View

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:32 25 4
gpt4 key购买 nike

在我的项目中,我一直在使用 Django 的通用 CRUD View 来处理很多事情。我现在想开始迁移到 DJango 1.3 中基于类的新样式通用 CRUD View 。我没有发现这些文档有多大帮助,并且可以使用一些帮助来转换我的一些基于函数的 View 。以下是我的部分观点:

def create_domains(request, *args, **kwargs):
return create_object(request=request, form_class=DomainForm,
template_name='customer/create_domains.html',
post_save_redirect=reverse('manage_domains')
)

def delete_domains(request, object_id, *args, **kwargs):
return delete_object(request=request,
object_id=object_id, model=Domain,
template_name='customer/delete_domains.html',
post_delete_redirect=reverse('manage_domains')
)

我想我会为第一个使用 CreateView,为下一个使用 DeleteView。这是我到目前为止想出的:

class DomainCreateView(CreateView):
form_class = DomainForm
template_name = 'create_domains.html'
success_url = 'manage_domains'

class DomainDeleteeView(CreateView):
model = Domain
template_name = 'delete_domains.html'
success_url = 'manage_domains'
pk_url_kwarg = object_id

你们谁能告诉我重写相同的基于类的 View 吗?快速启动会大有帮助,我相信我可以从那里开始。

谢谢。

最佳答案

在深入研究了 Django 源代码后,我发现了如何做到这一点。

class DomainCreateView(CreateView):
"""
Creates a Domain
"""
form_class = DomainForm
template_name = 'customer/create_domains.html'
success_url = reverse_lazy('manage_domains')

@method_decorator(login_required)
@method_decorator(only_managers_allowed)
def dispatch(self, *args, **kwargs):
"""
The Dispatcher
"""
return super(DomainCreateView, self).dispatch(*args, **kwargs)

def form_valid(self, form):
"""
Validate and save the form
"""
company = self.request.user.get_profile().company
self.object = form.save(company)
return super(ModelFormMixin, self).form_valid(form)


class DomainDeleteView(DeleteView):
"""
Deletes a Domain
"""
model = Domain
template_name = 'customer/delete_domains.html'
success_url = reverse_lazy('manage_domains')

@method_decorator(login_required)
@method_decorator(only_managers_allowed)
def dispatch(self, *args, **kwargs):
"""
The Dispatcher
"""
return super(DomainDeleteView, self).dispatch(*args, **kwargs)

关于python - 将旧的基于函数的通用 CRUD View 转换为新样式的基于类的通用 CRUD View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7460695/

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