Question

I've been using Django's generic CRUD views for quite a few things in my project. I'd now like to begin migrating to new style class-based generic CRUD views in DJango 1.3. I didn't finds the docs to be very help and could use a little help with converting some of my function-based views. Here's a snippet of my views:

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')
    )

I guess I'll be using a CreateView for the first one and a DeleteView for the next one. This is what I've come up with so far:

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

Could one of you show me to rewrite the same a class-based view? A little jump start would be a great help and I'm confident I could take it from there on.

Thanks.

Était-ce utile?

La solution

After digging through the Django sources I found out how to do it.

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top