Django Forms - 如何更改字段中的属性?

时间:2014-05-19 07:18:32

标签: django html5 django-models django-forms django-templates

Django表单功能为我的表单字段生成html代码。

我想更改某些属性或为该表单中的特定字段添加一些属性。

例如,我想为字段指定一个类。

我该怎么做?

我在SO上读到了一个答案,我可以这样做:

city = forms.CharField(widget=forms.TextInput(attrs={'class':'anyclass'}))

但是我得到一个错误,那个attrs不存在或者是未定义的......

更新

这是我的forms.py

来自django导入表单 来自HelloUprise.models导入目标 来自django.contrib.auth.models导入用户

class GoalForm(forms.ModelForm):
    deadline = forms.DateField(widget=forms.DateField(attrs={'class': 'form-control'}))


class Meta:
    model=Goal
    fields = ['goal', 'description', 'deadline', 'priority']

这是错误:

TypeError at /
__init__() got an unexpected keyword argument 'attrs'

回溯切换到复制并粘贴视图

get_response中的

C:\ Python27 \ lib \ site-packages \ django \ core \ handlers \ base.py                 resolver_match = resolver.resolve(request.path_info)... ▶本地变种 解决C:\ Python27 \ lib \ site-packages \ django \ core \ urlresolvers.py             对于self.url_patterns中的模式:... ▶本地变种 url_patterns中的C:\ Python27 \ lib \ site-packages \ django \ core \ urlresolvers.py         patterns = getattr(self.urlconf_module,“urlpatterns”,self.urlconf_module)...... ▶本地变种 urlconf_module中的C:\ Python27 \ lib \ site-packages \ django \ core \ urlresolvers.py             self._urlconf_module = import_module(self.urlconf_name)... ▶本地变种 import_module中的C:\ Python27 \ lib \ site-packages \ django \ utils \ importlib.py         导入(姓名)... ▶本地变种 C:\ Users \ Barosan \ Documents \ GitHub \ uprisedev \ UpriseApplication \ UpriseApplication \ urls.py in     url(r'^',include('HelloUprise.urls')),... ▶本地变种 C:\ Python27 \ lib \ site-packages \ django \ conf \ urls__init __。py in include         urlconf_module = import_module(urlconf_module)... ▶本地变种 import_module中的C:\ Python27 \ lib \ site-packages \ django \ utils \ importlib.py         导入(姓名)... ▶本地变种 C:\ Users \ Barosan \ Documents \ GitHub \ uprisedev \ UpriseApplication \ HelloUprise \ urls.py in 来自HelloUprise导入视图...... ▶本地变种 C:\ Users \ Barosan \ Documents \ GitHub \ uprisedev \ UpriseApplication \ HelloUprise \ views.py in 来自HelloUprise.forms导入GoalForm ... ▶本地变种 C:\ Users \ Barosan \ Documents \ GitHub \ uprisedev \ UpriseApplication \ HelloUprise \ forms.py in class GoalForm(forms.ModelForm):... ▶本地变种 GoalForm中的C:\ Users \ Barosan \ Documents \ GitHub \ uprisedev \ UpriseApplication \ HelloUprise \ forms.py     deadline = forms.DateField(widget = forms.DateField(attrs = {'class':'form-control'}))... ▶本地变种 init 中的C:\ Python27 \ lib \ site-packages \ django \ forms \ fields.py         super(BaseTemporalField,self)。 init (* args,** kwargs)... ▶本地大战

1 个答案:

答案 0 :(得分:1)

您还没有完成示例中显示的内容。您尝试传递该字段的另一个实例,而不是使用窗口小部件。这不起作用,如错误所示。

应该是:

deadline = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'}))

请注意使用DateInput代替DateField