views:

322

answers:

1

hi,

I actually want to accomplish the same thing a user in

http://stackoverflow.com/questions/365757/remembering-checked-checkboxes-across-pages-whats-the-best-way

asked. But not for php, I want it for django. Since django is just great :-)

I`m using pagination and want to remember the checked checkbox while the user is navigating over the pages provided by pagination.

Now I'm searching for a best practice how I could accomplish this. I do not really have a good idea how i could accomplish this. My idea would include javascript, but I'm sure there is somewhere out there a solution without js.

+1  A: 

I can't think of any way to do this with a paginator. But this is a good spot for a formwizard and dynamic forms. The general idea is to create a dynamic form for each "page" and then a formwizard to hold them all together. This allows for saving the checkboxes across multiple pages and lets you go backwards and forwards easily. The best thing is that it takes virtually no code!

Something like this should be able to deal with everything:

from django.contrib.formtools.wizard import FormWizard
from django import forms
from django.forms.extras.widgets import CheckboxSelectMultiple
from django.core.paginator import Paginator

# In your forms.py --------------


def MPageFormMaker(paginator):
    """
    Create a "paginated" group of forms based on a queryset and num-per-page item.
    """


    def Sform(this_q):
        """
        Create this page's items
        """
        class _PageForm(forms.Form):
            items = forms.ModelMultipleChoiceField(queryset = this_q,
                                widget = forms.CheckboxSelectMultiple)
        return _PageForm

    for i in range(paginator.num_pages):
        yield Sform(paginator.page(i).object_list)


class MpageForm(FormWizard):
    def done(self, request, formlist):
        #do something with the list of forms


#----- In your views.py

def MpageChecker(request):
    qset = Item.objects.all()

    paginator = Paginator(qset, 30)
    formwizard = MPageForm(list(MPageFormMaker(paginator)))

    #then deal with it like a normal formwizard

Essentially just instantiate the formwizard class and then let it take care of everything. Since it uses a paginator class to make the forms you can use any sort of personalization you'd like.

BTW: I haven't tested this code so it may have a few typos but it should be enough to get you on your way.

EDIT ... fix the ordering problem, now all ordering should be preserved correctly across pages!

JudoWill