[Answer]-I want to check some particular radiobutton in some radiobutton groups when page loads?

1👍

if i understand correctly, you want to let users change the content of the page, based on a few options you show them. i dont see yet what jQuery has to do here.

To show a form with previously checked boxes, you need to instantiate the form with this data. Same as edit views.

For example, if i have following form:

from django import forms

class MyForm(forms.Form):
    choice1 = forms.BooleanField(label='Choice A')
    choice2 = forms.BooleanField(label='Choice B')
    choice3 = forms.BooleanField(label='Choice C')

In view, i would instantiate it like this:

form = MyForm(initial={'choice1': True}

now when rendering in template:

<form action="" method="post">
    {{form.as_table}}
    <input type='submit' value='Submit'>
</form>

it will show choice1 as checked.

As you can see no jQuery was needed.

A few more things: you can’t store in view previously checked boxes. View is just a function, and all its variables are local. Look up python variable scope to understand what that means. If you want to store a choice, you can either have a model that will keep track of users’ choices, or save it in session, like this:

if form.is_valid():
  request.session['user_choice']=form.cleaned_data

This way you can use request.session['user_choice'] as initial data to instantiate the form.

This post has a very good explanation how to check what was checked using jQuery.

Anyways, it will much easier for you to have different view for each option, this way the code will be simpler, easier to maintain and test. And this way you can show buttons and not a form, no need to post, validate, instantiate.

👤Neara

Leave a comment