Multiple checkboxes

3,463 views
Skip to first unread message

Javier Nievas

unread,
Feb 3, 2006, 6:54:49 PM2/3/06
to Django users
Hello,

I have a list of items, each one with a checkbox to select it. I want
to post this info to a django view, but i don't know how should I use
the name="" and value="" of the input tag to gain access to it from
django as it if was an array.

I used something like that in PHP:

...
<input type="checkbox" name="array[<?php echo $id; ?>]" value="1"> Text
Text
...

So I was able to know what item's where selected very easy. Just make a
loop through the array post var, and check what id's have a "1" value.

I suppose there's an easy way to do something like that in django, but
don't know how.

Need some help.

Thanks in advance.

Maniac

unread,
Feb 3, 2006, 10:35:30 PM2/3/06
to django...@googlegroups.com
Javier Nievas wrote:

>I have a list of items, each one with a checkbox to select it. I want
>to post this info to a django view, but i don't know how should I use
>the name="" and value="" of the input tag to gain access to it from
>django as it if was an array.
>
>

Give them all the same name but different value.

<input type="checkbox" name="array" value="{{id}}">

Then when you submit a form browser will send values of checked
checkboxes and then in a view you can do

request.POST.getlist('myfield')

this'll give you normal Python list with values of all checked checkboxes.

Maniac

unread,
Feb 3, 2006, 10:47:33 PM2/3/06
to django...@googlegroups.com
Maniac wrote:

> Give them all the same name but different value.
>
> <input type="checkbox" name="array" value="{{id}}">
>
> Then when you submit a form browser will send values of checked
> checkboxes and then in a view you can do
>
> request.POST.getlist('myfield')

A typo: I meant 'myfield' and 'array' to be the same name but messed
them up when editing :-)

Amit Upadhyay

unread,
Feb 3, 2006, 11:26:01 PM2/3/06
to django...@googlegroups.com
On 2/4/06, Javier Nievas <javin...@gmail.com> wrote:

I have a list of items, each one with a checkbox to select it. I want
to post this info to a django view, but i don't know how should I use
the name="" and value="" of the input tag to gain access to it from
django as it if was an array.


The django way of  form processing is using formmanipulators, a very typical for handling view looks like this:

@login_required
def add_label_to_post(request, blog_id):
    blog = get_object_or_404(blogs, pk=blog_id)
    if blog.owner_id != request.user.id:
        return render_to_response('blogger/no_access', context_instance=DjangoContext(request))
    manipulator = AddLabelsToPostManipulator(blog)
    errors = new_data = {}
    if request.POST:
        # If data was POSTed
        new_data = request.POST.copy()
        # Check for errors.
        errors = manipulator.get_validation_errors(new_data)
        if not errors:
            # No errors. This means we can save the data!
            manipulator.do_html2python(new_data)
            manipulator.save(new_data)
            return HttpResponseRedirect("/blog/%s/" % id)
   
    form = formfields.FormWrapper(manipulator, new_data, errors)
    return render_to_response('blogger/add_label_to_post',
                              {'form': form},
                              context_instance=DjangoContext(request))

in short you should put all the details about form in a Manipulator class, and let it worry about validating and saving(whatever that means for your form) the form information. Django comes with a good collection of form items, or what can be called "widgets", they are defined in django/core/formfields.py, I recommend taking a look at the file itself as there is little documentation elsewhere, plus its pretty easy stuff [look for class FormField and its derived classes there].

For your case there is a CheckboxSelectMultipleField. To use it you have to define a Manipulator class:

class AddLabelsToPostManipulator(formfields.Manipulator):
    def __init__(self, blog):
        self.blog = blog
        self.fields = (
            formfields.TextField(field_name="url", is_required=True,
                                validator_list=[self.url_belongs_here]),
            formfields.CheckboxSelectMultipleField (field_name = 'label_ids',
                                          choices = [(label.id, label.name) for label in blog.get_label_list()],
                                          is_required=True)
        )

    def url_belongs_here(self, field_data, all_data):
        if not field_data.startswith(self.blog.url):
            raise validators.ValidationError, "Post does not belong here."

    def save(self, data):
       # whatever you want to do to handle the form, save it to db, send some mail, whatever
       # data is a dict, extract values, use data.getlist('label_ids') syntax when you are
       # are expecting multiple values. it will return a list. for other values, u can use data['url']
       # syntax. please note that if you do a data['label_ids'] which actually contains multiple
       # values, django will give you the first value out of it.
       # also there is no way to tell django if the values are infact integers, for multivalue selects,
       # django will make sure all the values are in the choice list that you provided to the
       # constructor, but when returning you the value, django will return you string representations


I used something like that in PHP:

...
<input type="checkbox" name="array[<?php echo $id; ?>]" value="1"> Text
Text
...

So I was able to know what item's where selected very easy. Just make a
loop through the array post var, and check what id's have a "1" value.

I suppose there's an easy way to do something like that in django, but
don't know how.

Need some help.

Thanks in advance.




--
Amit Upadhyay
Blog: http://www.rootshell.be/~upadhyay
+91-9867-359-701

Amit Upadhyay

unread,
Feb 3, 2006, 11:33:19 PM2/3/06
to django...@googlegroups.com
please ignore my prev mail, tab space combo in gmail!
       # so you may want to do a ids = map(int, data.getlist('label_ids') before further processing

You have to worry about list of possible coices while creating the AddLabelsToPostManipulator instance. choices is a list of tules, human readable text and the actual value that should represent that text, eg [(1, 'Some Label), (2, 'Some Other Label)] and so on. You can get some idea about how the template should look like on http://www.djangoproject.com/documentation/forms/

Javier Nievas

unread,
Feb 4, 2006, 2:42:51 AM2/4/06
to Django users
Thanks

Reply all
Reply to author
Forward
0 new messages