Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6551653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T12:21:50+00:00 2026-05-25T12:21:50+00:00

What is the djangoy way to approach this problem: In my form class, I

  • 0

What is the “djangoy” way to approach this problem:

In my form class, I have a forms.ChoiceField whose widget is a forms.RadioSelect widget, one of whose choices needs to be presented with an inline text input (which is also a field in the form). I’m using custom validation to ignore the text field when its radio choice is not selected. When rendered, I want it to appear like below:

<ul>
<li><label for="id_rad_0"><input type="radio" id="id_rad_0" value="none" name="rad" /> No Textbox</label></li>
<li><label for="id_rad_1"><input type="radio" id="id_rad_1" value="one" name="rad" /> One Textbox: <input type="text" name="bar" id="id_bar" /></label></li>
</ul>

However, I can’t simply produce this in my template, because the radio choices are not exposed. I can’t see a way to do this without tightly coupling my form to my template, or alternately, putting all of the presentation logic in the form class. What is the right way to solve this problem?

edit

I realize that the above might just be an obscure problem, but I’m not sure exactly what other information I can provide in order to inspire someone to help me with this. I’m a much better backend programmer than web designer, and I’m on this project alone, so maybe it’s a lack of education – is what I described simply poor design? Should I just be designing this a different way? I’m really open to any suggestion here that will help me move past this.

edit 2

Per request, the current code, shortened to save sanity, names changed to protect the innocent:

# forms.py
from myapp.models import RatherComplicatedModel
from django import forms

class RatherComplicatedForm(forms.ModelForm):
    #various and sundry code...
    RADIO_CHOICES = (
        ('none', "No Textbox"),
        ('one', "One Textbox: "),
    )
    # although I've abbreviated the model, 'rad' does not appear in the model;
    # it merely provides input to the un-provided clean function
    rad = forms.ChoiceField(widget=forms.RadioSelect(),choices=RADIO_CHOICES)

    class Meta:
        model = RatherComplicatedModel

–

# models.py
from django.db import models

class RatherComplicatedModel(models.Model):
    #some other stuff...
    bar = models.IntegerField(blank=True,null=True)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T12:21:51+00:00Added an answer on May 25, 2026 at 12:21 pm

    Anton’s answer worked, and was a decent answer for a while there – but unfortunately it became unmaintainable. So, taking a cue from a diff attached to django ticket #9230, I just monkey patched django.forms.forms.BoundField

    from django import forms
    
    def MonkeyPatchDjangoFormsBoundField():
        def prepare_widget_render(self, widget=None, attrs=None, only_initial=False):
            """
            Prepare the data needed for the widget rendering.
            """
            if not widget:
                widget = self.field.widget
    
            attrs = attrs or {}
            auto_id = self.auto_id
            if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
                if not only_initial:
                    attrs['id'] = auto_id
                else:
                    attrs['id'] = self.html_initial_id
    
            if not only_initial:
                name = self.html_name
            else:
                name = self.html_initial_name
    
            return widget, name, attrs
    
        def as_widget(self, widget=None, attrs=None, only_initial=False):
            """
            Renders the field by rendering the passed widget, adding any HTML
            attributes passed as attrs.  If no widget is specified, then the
            field's default widget will be used.
            """
            widget, name, attrs = self.prepare_widget_render(widget, attrs, only_initial)
            return widget.render(name, self.value(), attrs=attrs)
    
        def __iter__(self):
            """
            Check if current widget has a renderer and iterate renderer.
            """
            widget, name, attrs = self.prepare_widget_render()
            if not hasattr(widget, 'get_renderer'):
                raise Exception, "Can not iterate over widget '%s'" % widget.__class__.__name__
            renderer = widget.get_renderer(name, self.value(), attrs=attrs)
            for entry in renderer:
                yield entry
    
        def __getitem__(self,idx):
            """
            Tries to use current widget's renderer, and then check attribute.
            """
            widget, name, attrs = self.prepare_widget_render()
            try:
                renderer = widget.get_renderer(name, self.value(), attrs=attrs)
                return renderer[idx]
            except Exception:
                return getattr(self,idx)
    
        forms.forms.BoundField.prepare_widget_render = prepare_widget_render
        forms.forms.BoundField.as_widget = as_widget
        forms.forms.BoundField.__iter__ = __iter__
        forms.forms.BoundField.__getitem__ = __getitem__
    

    This allowed me to be able to access the radio inputs directly, by using {{ form.field.0.tag }}, or through iteration – {% for radio in form.field %} {{ radio.tag }} {% endfor %}. Much easier to take care of!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When I define a Django form class similar to this: def class MyForm(forms.Form): check
I have a query that I'm trying to figure the django way of doing
What is the correct way to do conditional formatting in Django? I have a
I'm trying to set custom 'name' attribute in django form. I've been trying this
I've been looking for a better way to deal with site-specific settings (in this
So let's say I have jQuery convert a simple text input from this <input
I am using Django's class based generic views in a blog application. One of
I'm trying to find an easy way to build forms which show dates in
What's a djangonautic way of handling default settings in an app if one isn't
I have a Django project, that has a Address model. This is used in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.