0

I have a form with the option to select multiple checkboxes, however when I try and retrieve the key from the dictionary in the post request. It only provides the first value of the array(may not be an array). I would like to retrieve all the data points.

Models

class CreateJournalistForm(forms.Form):

    vertical_choices = (('General', 'General'), ('News', 'News'), ('Life', 'Life'), ('Money', 'Money'), ('Sports', 'Sports'), ('Entertainment', 'Entertainment'), ('Dating', 'Dating'), ('Music', 'Music'), ('Humor', 'Humor'))

    name = forms.CharField(max_length=40, required=False)
    verticals = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple, choices=vertical_choices)
    location = forms.CharField(max_length=40)

View

def journalist(request):
    if request.method == "POST":
        form = CreateJournalistForm(request.POST)
        pdb.set_trace()
        if not form.data['name']:
            if form.is_valid():
                form.save()
                return HttpResponse("Thank you for applying.  We hope to get back to you soon")
            else:
                return HttpResponse("Sorry there was an error processing your application. Note: All fields on the application are required.")
        else:
            return HttpResponse("Thank you for applying.  We hope to get back to you soon")
    elif request.method == "GET":
        form = CreateJournalistForm()
    return render_to_response('journalist_application.html', {'form': form}, context_instance=RequestContext(request))

In pry debugger request post will provide:

<QueryDict: {u'sample': [u'sdfsdf'], u'first_name': [u'sdfsd'], u'last_name': [u'sdfsf'], u'name': [u''], u'dob': [u'1/22/13'], u'twitter': [u'sdfsdf'], u'ideas': [u'sdfsdf'], u'contribution': [u'sdf'], u'verticals': [u'General', u'News', u'Life', u'Money', u'Sports'], u'google': [u'sdfsdf'], u'location': [u'sdfsdf']}

This is provided by request.POST in debugger. Now if I provide the key request.POST['verticals'] it will only return one object in the array. u'Sports'

1 Answer 1

1

I don't know why you want to access the request directly, since you have a form and it is taking care of converting the params into an object.

However, you can use request.POST.getlist('verticals') to get all the values for a key.

Sign up to request clarification or add additional context in comments.

2 Comments

that works! how might i use the form to get the data?
You should be using form.cleaned_data to access the data after form validation. This is all explained in the forms docs, as is the correct pattern to show errors to the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.