Django:如何使用 ModelForm 隐藏/覆盖默认标签?

发布于 2025-01-06 06:32:27 字数 541 浏览 0 评论 0原文

我有以下内容,但为什么这不隐藏图书评论的标签?我收到错误“文本字段”未定义:

from django.db import models
from django.forms import ModelForm, Textarea

class Booklog(models.Model):
    Author = models.ForeignKey(Author)
    Book_comment = models.TextField()
    Bookcomment_date = models.DateTimeField(auto_now=True)

class BooklogForm(ModelForm):
    #book_comment = TextField(label='')

    class Meta:
        model = Booklog
        exclude = ('Author')
        widgets = {'book_entry': Textarea(attrs={'cols': 45, 'rows': 5}, label={''}),}  

i have the following, but why does this not hide the label for book comment? I get the error 'textfield' is not defined:

from django.db import models
from django.forms import ModelForm, Textarea

class Booklog(models.Model):
    Author = models.ForeignKey(Author)
    Book_comment = models.TextField()
    Bookcomment_date = models.DateTimeField(auto_now=True)

class BooklogForm(ModelForm):
    #book_comment = TextField(label='')

    class Meta:
        model = Booklog
        exclude = ('Author')
        widgets = {'book_entry': Textarea(attrs={'cols': 45, 'rows': 5}, label={''}),}  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

淤浪 2025-01-13 06:32:27

为了扩展我上面的评论,没有用于表单的文本字段。这就是您的 TextField 错误告诉您的内容。在您拥有有效的表单字段之前,无需担心标签。

解决方案是使用 forms.CharField 代替,并带有 Textarea 小部件。您可以使用模型表单小部件选项,但在定义字段时设置小部件更简单。

一旦您拥有有效的字段,您就已经知道如何设置空白标签:只需在字段定义中使用 label='' 即可。

# I prefer to importing django.forms
# but import the fields etc individually
# if you prefer 
from django import forms

class BooklogForm(forms.ModelForm):
    book_comment = forms.CharField(widget=forms.Textarea, label='')

    class Meta: 
        model = Booklog
        exclude = ('Author',)

To expand on my comment above, there isn't a TextField for forms. That's what your TextField error is telling you. There's no point worrying about the label until you have a valid form field.

The solution is to use forms.CharField instead, with a Textarea widget. You could use the model form widgets option, but it's simpler to set the widget when defining the field.

Once you have a valid field, you already know how to set a blank label: just use the label='' in your field definition.

# I prefer to importing django.forms
# but import the fields etc individually
# if you prefer 
from django import forms

class BooklogForm(forms.ModelForm):
    book_comment = forms.CharField(widget=forms.Textarea, label='')

    class Meta: 
        model = Booklog
        exclude = ('Author',)
夏末的微笑 2025-01-13 06:32:27

如果您使用的是 Django 1.6+,则 ModelForm 的元类中添加了许多新的覆盖,包括标签和 field_classes

请参阅: https://docs.djangoproject .com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields

If you're using Django 1.6+ a number of new overrides were added to the meta class of ModelForm, including labels and field_classes.

See: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields

一花一树开 2025-01-13 06:32:27

要仅覆盖标签,您可以执行以下操作

def __init__(self, *args, **kwargs): 
    super(ModelForm, self).__init__(*args, **kwargs)
    self.fields['my_field_name'].label = 'My New Title'

To override just the label you can do

def __init__(self, *args, **kwargs): 
    super(ModelForm, self).__init__(*args, **kwargs)
    self.fields['my_field_name'].label = 'My New Title'
沧桑㈠ 2025-01-13 06:32:27

下面找到了一个简单的解决方案:
https://docs.djangoproject.com /en/1.10/topics/forms/modelforms/#overriding-the-default-fields

基本上只需添加标签字典并在表单元类中输入所需的新标签即可。

class AuthorForm(ModelForm):
class Meta:
    model = Author
    fields = ('name', 'title', 'birth_date')
    labels = {
        'name': _('Writer'),
    }

Found an easy solution below:
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields

Basically just add labels dictionary and type the new label you want in your forms meta class.

class AuthorForm(ModelForm):
class Meta:
    model = Author
    fields = ('name', 'title', 'birth_date')
    labels = {
        'name': _('Writer'),
    }
缱倦旧时光 2025-01-13 06:32:27

exclude 属性采用可迭代对象(通常是列表或元组)。但 ('book') 不是一个元组;由于 Python 语法的怪异,您需要附加一个逗号以使其成为元组:exclude = ('book',)

因此,我通常只使用列表:exclude = ['book']。 (从语义上讲,无论如何在这里使用列表更有意义;我不确定为什么 Django 的文档鼓励使用元组。)

The exclude attribute takes an iterable (usually a list or tuple). But ('book') is not a tuple; you need to append a comma to make it a tuple, due to a quirk of Python's syntax: exclude = ('book',).

For this reason, I usually just use lists: exclude = ['book']. (Semantically, it makes more sense to use lists here anyway; I'm not sure why Django's documentation encourages the use of tuples instead.)

薄荷梦 2025-01-13 06:32:27

首先,将该字段放入 Meta 类中。它需要继续实际的ModelForm。其次,无论如何,这都不会达到预期的结果。它只会在 HTML 中打印一个空标签元素。

如果您想完全删除标签,请手动检查该字段并且不显示标签:

{% for field in form %}
    {% if field.name != 'book_comment' %}
    {{ field.label }}
    {% endif %}
    {{ field }}
{% endfor %}

或者使用 JavaScript 将其删除。

First off, you put the field in the Meta class. It needs to go on the actual ModelForm. Second, that won't have the desired result anyways. It will simply print an empty label element in the HTML.

If you want to remove the label completely, either manually check for the field and don't show the label:

{% for field in form %}
    {% if field.name != 'book_comment' %}
    {{ field.label }}
    {% endif %}
    {{ field }}
{% endfor %}

Or use JavaScript to remove it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文