开发者

How to create Django form with mutually exclusive radiobuttons?

I need a 开发者_如何转开发form with two (mutually exclusive) radio buttons and with some other controls between them. I mean i need form like this:

How to create Django form with mutually exclusive radiobuttons?

Here I found a way to make a boolean field with two mutually exclusive radio buttons, but I have no idea how to insert other controls between them.


I suggest you split this into two (or more) separate Django forms with some client-side JS to do the enable/disable of each set of fields when clicking the radio buttons (which themselves aren't part of any Django form).

eg

class FormA(forms.Form):
    some_field = forms.CharField()
    other_field = forms.CharField()

class FormB(forms.Form):
    third_field = forms.CharField()
    one_more_field = forms.CharField()

in your view:

def my_view(request):
    form_a = None
    form_b = None

    if request.POST:
        if request.POST['choice_field'] == 'a':
            form_a = FormA(prefix='a', data=request.POST)
            if form_a.is_valid():
                # do something
        if request.POST['choice_field'] == 'b':
            form_b = FormB(prefix='b', data=request.POST)
            if form_b.is_valid():
                # do something

    form_a = form_a or FormA(prefix='a')
    form_b = form_b or FormA(prefix='b')

    context = {
        'form_a': form_a,
        'form_b': form_b,
    }
    return render_to_response("my_form.html", context, RequestContext(request))

in your template:

<form action="" method="post">
  <input type="radio" name="choice_field" value="a" />
  <ul>
      {{ form_a.as_ul }}
  </ul>
  <input type="radio" name="choice_field" value="b" />
  <ul>
      {{ form_b.as_ul }}
  </ul>
  <input type="submit" value="Submit" />
</form>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜