Doubt about the way to show a form

2

Good evening, I have a form created in the following way:

(in forms)

RESULTADO_P = (
    ('a', 'a'),
    ('b', 'b'),
    ('c', 'c'),
    ('?', '?'),
    )


class formulario(forms.Form):
   r1 = forms.ChoiceField(choices=RESULTADO_P, initial='?')

(in index)

{{form.r1}}

and it is shown to me in the following way:

My question is how I could get those options to be displayed in 4 checkboxes and for the user to choose one of them.

Thanks for the answers.

    
asked by user5872256 07.02.2016 в 15:17
source

2 answers

1

Then you must use the MultipleChoiceField field in the model. The widget SelectMultiple that has the same syntax is used in the form.

The reference in the official documentation for the field MultipleChoiceField and for SelectMultiple .

    
answered by 07.02.2016 / 15:21
source
0

I do not understand very well what you want to achieve, if you want to show several checkboxes and that you can choose only one option, then what you need is to change the Widget to RadioSelect to use radio buttons and the user can only choose one option:

from django import forms
from django.forms import widgets

class formulario(forms.Form):
    r1 = forms.ChoiceField(
        choices=RESULTADO_P, 
        widget=widgets.RadioSelect
    )

If you want to use multiple selection, you should use what @toledano indicates and change to MultipleChoiceField :

from django import forms

class formulario(forms.Form):
    r1 = forms.MultipleChoiceField(
        choices=RESULTADO_P, 
        initial='?'
    )

I do not know if the options you have created are appropriate, if you are going to switch to multiple selection you may no longer need the ? option:

RESULTADO_P = (
    ('a', 'a'),
    ('b', 'b'),
    ('c', 'c'),
)

class formulario(forms.Form):
    r1 = forms.MultipleChoiceField(choices=RESULTADO_P)

Still, it is possible to continue using the initial parameter on your form. for example, if you want the options a and c to be selected initially, you can pass a list as a parameter:

class formulario(forms.Form):
    r1 = forms.MultipleChoiceField(choices=RESULTADO_P, initial=['a', 'c'])

Now, to change the selection to checkbox, you only have to modify the Widget you use for that field and use CheckboxSelectMultiple :

from django import forms
from django.forms import widgets

class formulario(forms.Form):
    r1 = forms.MultipleChoiceField(
        choices=RESULTADO_P, 
        widget=widgets.CheckboxSelectMultiple
    )

On the other hand, it would be good to explain what you want to achieve by saying that the result is shown in horizontal form . It occurs to me that you can get it using CSS.

    
answered by 07.02.2016 в 17:07