我在项目中使用了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


你们中的一个能告诉我重写相同的基于类的视图吗?稍微起步将是一个很大的帮助,我相信我可以从那里开始。

谢谢。

最佳答案

深入研究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/

10-14 02:52