覆盖Django formfields / models上的标签

时间:2014-08-10 11:15:24

标签: django django-models django-forms

我正在尝试编辑我的网页上显示的表单字段的标签。我遵循与Django文档相同的格式,如以下链接所示: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#overriding-the-default-fields。但是,我的标签保持不变。我正在使用Django 1.6.5,所以它绝对应该支持标签覆盖。有什么想法吗?

我的代码如下:

#forms.py
from django.forms import ModelForm, RadioSelect
from webpage.models import Career
from django.utils.translation import ugettext_lazy as _
class ApplyForm(ModelForm):
    class Meta:
        model= Career
        fields=['name','email','phone','position_desired','street_address','city','state','zip_code','high_school','hsloc','hssub','hsyears','hsgrad']
        widgets = {
            'hsgrad': RadioSelect,
        }
        labels = {
            'hsloc': _('Location: '),
            'hssub': _('Subject(s) Studied/Degree(s) Received: '),
            'hsyears': _('Years Completed: '),
            'hsgrad': _('Did you graduate? '),
        }

#models.py
from django.db import models
from localflavor.us.models import PhoneNumberField, USStateField, ZipCodeField

BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))

# Create your models here.
class Career(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField(max_length=30)
    phone=PhoneNumberField()
    position_desired=models.CharField(max_length=50, blank=True, null=True)
    street_address=models.CharField(max_length=50)
    city=models.CharField(max_length=30)
    state=USStateField()
    zip_code=ZipCodeField()

    high_school = models.CharField(max_length=50)
    hsloc = models.CharField(max_length=50)
    hssub = models.CharField(max_length=50)
    hsyears = models.CharField(max_length=10)
    hsgrad = models.BooleanField(choices=BOOL_CHOICES, blank=False, default='Unspecified')

1 个答案:

答案 0 :(得分:0)

它应该定义忽略它们:

来自Django文档:

  

ModelForm是一个可以自动生成某些字段的常规表单。自动生成的字段取决于Meta类的内容以及已经以声明方式定义的字段。 基本上,ModelForm只生成表单中缺少的字段,或者换言之,未声明地定义的字段

     

以声明方式定义的字段保持原样,因此保留   对Meta属性(如小部件,标签)进行的自定义   help_texts或error_messages被忽略;这些仅适用于领域   这是自动生成的。

直接在模型中声明您的标签:

class Career(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField(max_length=30)
    phone=PhoneNumberField()
    position_desired=models.CharField(max_length=50, blank=True, null=True)
    street_address=models.CharField(max_length=50)
    city=models.CharField(max_length=30)
    state=USStateField()
    zip_code=ZipCodeField()

    high_school = models.CharField(max_length=50)
    hsloc = models.CharField(_('Location'),max_length=50)
    hssub = models.CharField(_('Subject(s) Studied/Degree(s) Received'),max_length=50)
    hsyears = models.CharField(_('Years Completed'),max_length=10)
    hsgrad = models.BooleanField(_('Did you graduate?'),choices=BOOL_CHOICES, blank=False, default='Unspecified')