python 从 Django 的 TextArea 小部件中删除标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1080650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:25:54  来源:igfitidea点击:

Removing the Label From Django's TextArea Widget

pythondjangotextarealabelwidget

提问by AlbertoPL

How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:

如何删除附加到我尝试与 Django 一起使用的 TextArea 的标签?我正在尝试查找有关此问题的任何信息,但似乎找不到与我的问题相关的任何信息。这就是我在我的代码中所做的:

class CommentForm(forms.Form):
    comment = forms.CharField(widget=forms.Textarea())

This is the HTML that it produces:

这是它生成的 HTML:

<label for="id_text">Text:</label> 
<textarea id="id_text" rows="10" cols="40" name="text"></textarea>

That label is no good and I'd like a way to remove it. That code was produced via:

那个标签不好,我想要一种方法来去除它。该代码是通过以下方式生成的:

{{ form.as_p }}

(I removed the paragraph tags because they are irrelevant)

(我删除了段落标签,因为它们无关紧要)

EDIT: I added the class CommentForm part for further clarification.

编辑:我添加了类 CommentForm 部分以进一步说明。

Anyone have any suggestions?

有人有什么建议吗?

采纳答案by Grzegorz Oledzki

The Django documentation on customizing labelssays it could be turned off with auto_idargument to Form constructor:

关于自定义标签Django 文档说它可以通过auto_id表单构造函数的参数关闭:

f = ContactForm(auto_id=False)

回答by lemonad

This should work with the latest version (trunk) of django:

这应该适用于最新版本(主干)的 django:

comment = forms.CharField(label="", help_text="", widget=forms.Textarea())

Hope that helps!

希望有帮助!

回答by Persijn

Try this in your form:

在您的表单中尝试此操作:

def __init__(self, *args, **kwargs):
    self.fields['comment'].label = ''

But for newer versions of django i prefer Iemonad's answer

但是对于较新版本的 django,我更喜欢 Iemonad 的回答

回答by Kyle_397

Not sure about old Django but u can now empty the form field labels in Meta for the new Django

不确定旧 Django,但您现在可以为新 Django 清空 Meta 中的表单字段标签

class CustomForm(forms.Form):
    class Meta:
        ...  #other properties such as model, fields, widgets and help text
        labels = {
           'comment' : '',
        }

回答by Kyle_397

A quick-and-dirty solution would be to iterate through the form manualy (with {% for field in form %}) and handle the "problematic" field specially. You could also override the as_p/as_table methods if needed.

一个快速而肮脏的解决方案是手动遍历表单(使用 {% for field in form %})并专门处理“有问题”的字段。如果需要,您还可以覆盖 as_p/as_table 方法。