在我的项目中,我一直在使用Django的通用CRUD视图。我现在想开始在DJango 1.3中迁移到基于类的基于类的通用CRUD视图。我没有发现文档非常有帮助,可以使用一些帮助来转换我的一些基于函数的视图。以下是我的观点片段:
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
你们当中有人能告诉我重写同一个基于类的视图吗?一个小小的启动将是一个很大的帮助,我相信我可以从那里开始。
感谢。
答案 0 :(得分:3)
在深入了解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)