如何创建在复选框右侧显示复选框标签的 Django 表单? [英] How do I create a Django form that displays a checkbox label to the right of the checkbox?

查看:21
本文介绍了如何创建在复选框右侧显示复选框标签的 Django 表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我定义一个类似这样的 Django 表单类时:

When I define a Django form class similar to this:

def class MyForm(forms.Form):
    check = forms.BooleanField(required=True, label="Check this")

它扩展为 HTML,如下所示:

It expands to HTML that looks like this:

<form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>

我希望复选框输入元素在复选框后面有一个标签,而不是相反.有没有办法说服 Django 这样做?

I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?

感谢 Jonas 的回答 - 尽管如此,虽然它解决了我询问的问题(复选框标签呈现在复选框的右侧),但它引入了一个新问题(所有小部件标签都呈现在其小部件的右侧...)

Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)

我想避免覆盖 _html_output() 因为它显然不是为它设计的.我想出的设计是在 Field 类中实现一个字段 html 输出方法,覆盖 Boolean 字段的方法并在 _html_output() 中使用该方法.遗憾的是,Django 开发人员选择了不同的方式,我希望尽可能在现有框架内工作.

I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible.

CSS 听起来是一个不错的方法,只是我不知道足够的 CSS 来实现这一点,甚至无法决定我是否喜欢这种方法.此外,我更喜欢与最终输出相似的标记,至少在渲染顺序上是这样.

CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.

此外,由于对于任何特定标记有多个样式表是合理的,在 CSS 中执行此操作可能意味着必须为多种样式执行多次,这几乎使 CSS 成为错误的答案.

Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer.

好像我在下面回答我自己的问题.如果有人有更好的想法如何做到这一点,请不要害羞.

Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.

推荐答案

这是我最终要做的.我编写了一个自定义模板 stringfilter 来切换标签.现在,我的模板代码如下所示:

Here's what I ended up doing. I wrote a custom template stringfilter to switch the tags around. Now, my template code looks like this:

{% load pretty_forms %}
<form action="." method="POST">
{{ form.as_p|pretty_checkbox }}
<p><input type="submit" value="Submit"></p>
</form>

与普通 Django 模板的唯一区别是添加了 {% load %} 模板标签和 pretty_checkbox 过滤器.

The only difference from a plain Django template is the addition of the {% load %} template tag and the pretty_checkbox filter.

这是 pretty_checkbox 的一个功能性但丑陋的实现 - 此代码没有任何错误处理,它假定 Django 生成的属性以非常特定的方式格式化,这将是一个糟糕的在你的代码中使用这样的东西的想法:

Here's a functional but ugly implementation of pretty_checkbox - this code doesn't have any error handling, it assumes that the Django generated attributes are formatted in a very specific way, and it would be a bad idea to use anything like this in your code:

from django import template
from django.template.defaultfilters import stringfilter
import logging

register=template.Library()

@register.filter(name='pretty_checkbox')
@stringfilter
def pretty_checkbox(value):
    # Iterate over the HTML fragment, extract <label> and <input> tags, and
    # switch the order of the pairs where the input type is "checkbox".
    scratch = value
    output = ''
    try:
        while True:
            ls = scratch.find('<label')
            if ls > -1:
                le = scratch.find('</label>')
                ins = scratch.find('<input')
                ine = scratch.find('/>', ins)
                # Check whether we're dealing with a checkbox:
                if scratch[ins:ine+2].find(' type="checkbox" ')>-1:
                    # Switch the tags
                    output += scratch[:ls]
                    output += scratch[ins:ine+2]
                    output += scratch[ls:le-1]+scratch[le:le+8]
                else:
                    output += scratch[:ine+2]
                scratch = scratch[ine+2:]
            else:
                output += scratch
                break
    except:
        logging.error("pretty_checkbox caught an exception")
    return output

pretty_checkbox 扫描其字符串参数,找到成对的 <label>和<输入>标签,如果 <input>标签的类型是复选框".它还去除了标签的最后一个字符,也就是:"字符.

pretty_checkbox scans its string argument, finds pairs of <label> and <input> tags, and switches them around if the <input> tag's type is "checkbox". It also strips the last character of the label, which happens to be the ':' character.

优点:

  1. 不使用 CSS.
  2. 标记最终看起来像它应该的样子.
  3. 我没有破解 Django 内部结构.
  4. 该模板很好、紧凑且符合地道.

缺点:

  1. 需要针对标签和输入字段名称的令人兴奋的值测试过滤器代码.
  2. 可能有什么地方可以做得更好更快.
  3. 比我计划在星期六做的工作要多.

这篇关于如何创建在复选框右侧显示复选框标签的 Django 表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆