djangodjango-formwizard

How to make a django field like a RadioSelector inside a django form wizard


I need to define one field of my django model in a way that takes either X/Z, True/False or 0/1. I mean when I select one checkbox I expect be able to choose just one checkbox not both together(Like select between Yes or No) and after submit I see one of those mentioned values in the database table field.

What I have tried so far:

from model_utils import Choices
class Post(models.Model):
     STATUS = Choices(
       ('x', ('select X')),
       ('z', ('Select Z'))
     )

    action_style = models.CharField(
        max_length=32,
        choices=STATUS,
        default='x'
        )

and in form:

class Postform(forms.ModelForm):

    STATUS = Choices(
           ('x', 'select X'),
           ('z', 'Select Z')
         )

    status = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        required=False, choices=STATUS
    )

    class Meta:
        model = Post
        fields = ['status']

and in template:

<form method="POST" action="" enctype="multipart/form-data">
            {% csrf_token %}
            {{ wizard.management_form }}
            {{ wizard.form.action_style }}
             <input type="submit" value="submit"/>
</form>

Solution

  • This might cause problem for choosing only one.

    forms.CheckboxSelectMultiple
    

    According to django Doc about CheckboxSelectMultiple and related SelectMultiple, it allows multiple selection: <select multiple>...</select>

    You might need CheckBoxInput3 or use RadioSelect 4.

    in forms.py, replace

    status = forms.MultipleChoiceField(
            widget=forms.CheckboxSelectMultiple,
            required=False, choices=STATUS
        )
    

    with

    status = forms.MultipleChoiceField(
            widget = forms.RadioSelect(choices=STATUS)
        )