当前位置:  开发笔记 > 编程语言 > 正文

Django表单 - 设置标签

如何解决《Django表单-设置标签》经验,为你挑选了4个好方法。

我有一个继承自其他两种形式的表格.在我的表单中,我想更改在其中一个父表单中定义的字段的标签.有谁知道如何做到这一点?

我正在尝试在我的网站上执行此操作__init__,但它会抛出一个错误,指出"'RegistrationFormTOS'对象没有属性'email'".有谁知道我怎么做到这一点?

谢谢.

这是我的表单代码:

from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationFormUniqueEmail
from registration.forms import RegistrationFormTermsOfService

attrs_dict = { 'class': 'required' }

class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
    """
    Subclass of ``RegistrationForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.

    """
    email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address'))

    def __init__(self, *args, **kwargs):
        self.email.label = "New Email Label"
        super(RegistrationFormTOS, self).__init__(*args, **kwargs)

    def clean_email2(self):
        """
        Verifiy that the values entered into the two email fields
        match. 
        """
        if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
            if self.cleaned_data['email'] != self.cleaned_data['email2']:
                raise forms.ValidationError(_(u'You must type the same email each time'))
        return self.cleaned_data

小智.. 126

你应该使用:

def __init__(self, *args, **kwargs):
    super(RegistrationFormTOS, self).__init__(*args, **kwargs)
    self.fields['email'].label = "New Email Label"

首先请注意您应该使用超级呼叫.



1> 小智..:

你应该使用:

def __init__(self, *args, **kwargs):
    super(RegistrationFormTOS, self).__init__(*args, **kwargs)
    self.fields['email'].label = "New Email Label"

首先请注意您应该使用超级呼叫.



2> 小智..:

以下是覆盖默认字段的示例:

from django.utils.translation import ugettext_lazy as _

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }


这仅适用于ModelForm.不是表格

3> Matthew Mars..:

您可以通过'fields'字典访问表单中的字段:

self.fields['email'].label = "New Email Label"

这样您就不必担心与表单类方法存在名称冲突的表单字段.(否则你不能有一个名为'clean'或'is_valid'的字段.)直接在类体中定义字段主要是为了方便.



4> kiennt..:

label定义表单时,可以将其设置为字段的属性.

class GiftCardForm(forms.ModelForm):
    card_name = forms.CharField(max_length=100, label="Cardholder Name")
    card_number = forms.CharField(max_length=50, label="Card Number")
    card_code = forms.CharField(max_length=20, label="Security Code")
    card_expirate_time = forms.CharField(max_length=100, label="Expiration (MM/YYYY)")

    class Meta:
        model = models.GiftCard
        exclude = ('price', )

推荐阅读
贾志军
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有