【问题标题】:customize radio buttons in django在 django 中自定义单选按钮
【发布时间】:2013-05-22 08:01:01
【问题描述】:

模板代码是

{{ form.incident_live }}

forms.py

INCIDENT_LIVE = (
    ('0', 'Live'),
    ('1', 'Test'),
)
class IncidentForm(forms.ModelForm):
     incident_live = forms.ChoiceField(widget=forms.RadioSelect(),choices=INCIDENT_LIVE)

上面的代码给了我垂直顺序选择的单选按钮,但我希​​望它是水平的,即等效的 html 将是<input type="radio" name="status" />Live <input type="radio" name="status" checked="checked"/> Test

提前致谢

【问题讨论】:

标签: django django-forms django-templates


【解决方案1】:

听起来像是自定义小部件渲染器的工作:

from django.utils.safestring import mark_safe

class HorizRadioRenderer(forms.RadioSelect.renderer):
    """ this overrides widget method to put radio buttons horizontally
        instead of vertically.
    """
    def render(self):
            """Outputs radios"""
            return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class IncidentForm(forms.ModelForm):
     incident_live = forms.ChoiceField(widget=forms.RadioSelect(renderer=HorizRadioRenderer),choices=INCIDENT_LIVE)

取自https://wikis.utexas.edu/display/~bm6432/Django-Modifying+RadioSelect+Widget+to+have+horizontal+buttons

【讨论】:

  • 刚刚没有测试,得到这个错误“Caught NameError while rendering: global name 'mark_safe' is not defined”
  • 哦,好的,添加了import语句,试试看。
  • 是的,它工作正常,我接受了你的回答。还有一个问题是可以减少两个选项之间的空间,因为两个选项之间的空间超过 2 英寸,需要减少最低限度。
  • 突然意识到这个问题已经在这里问过了——标记为重复。如果你这样尝试:mark_safe(u'\n'.join([u'%s\n' % w.strip() for w in self]))
【解决方案2】:

“alecxe”的这种解决方案实际上对我不起作用。 但是添加 CSS 代码确实有效:

{% block style %}
<style>
    .radio{
    display:inline-block;
    }
</style>
{% endblock %}

【讨论】:

  • 很好,这很好用(虽然我必须做#key-pic li {display: inline;},其中key-pic 是包含列表的div-id。)不知道为什么人们使用更复杂的版本。
【解决方案3】:

根据 Django 文档,'attrs' 是一个字典,其中包含要在呈现的小部件上设置的 HTML 属性。

考虑到这一点,一个简单的基于表单的解决方案将类似于以下内容:

class IncidentForm(forms.ModelForm):
    incident_live = forms.ChoiceField(
        widget=forms.RadioSelect(attrs={
            'display': 'inline-block',
        }),
        choices=INCIDENT_LIVE
    )

【讨论】:

    【解决方案4】:

    <head>
    
        <style>
    
            #try li{
            display:inline-block; }
    
        </style>
    
    <head>
    
    <body>
    
        <form id="try" class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
    
             {% csrf_token %}
             {{ form.as_p}}                       
            <button type="submit" class="btn btn-
                  success">Submit</button> 
    
        </form> 
    
     </body>
    

    【讨论】:

    • 请评论你的答案。
    【解决方案5】:

    实际上,解决方案应该非常简单。这一切都在 Django documentation 中。

    这是我在一些表格中所做的:

    在布局表单字段的模板中,我将这样做:

    {% for field in form.visible_fields %}
        {{ field.errors }}
        {% if field.name == "<some_field_name>" %}
        ...
        ...
        {% elif field.name == "<radio_field_name>" %}
            {% for radio in field %}
                <label for="{{ radio.id_for_label }}">
                    {{ radio.choice_label }}
                    <span class="radio">{{ radio.tag }}</span>
                </label>
            {% endfor %}
        {% endif %}
    
    {% endfor %}
    

    结果单选:

    到目前为止,这已经奏效了。

    【讨论】:

      【解决方案6】:

      user12379095 的启发下,我想出了这个让收音机与 Bootstrap 一起工作的方法。供我这种对HTML和CSS一窍不通的人参考。这是使用 Boostrap 5、Django 3.1.6:

      在 forms.py 中:

      from django import forms
      
      class ExampleForm(forms.Form):
          choice = forms.ChoiceField(
              label = 'test',
              choices = zip([1,2,3], ['a','b','c']),
              widget = forms.RadioSelect(
                  attrs = {'class' : 'form-check-input'}
              )
          )
      

      在 html 模板中:

              {% for field in form.visible_fields %}
                  {{ field.errors }}
                  {% for radio in field %}
                      <div class="form-check form-check-inline">
                          {{ radio }}
                      </div>
                  {% endfor %}
              {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2014-08-19
        • 2013-05-08
        • 2015-02-27
        • 1970-01-01
        • 2019-10-11
        • 2021-04-23
        • 2018-10-08
        • 2015-08-16
        • 2012-07-25
        相关资源
        最近更新 更多