Django中的form如何设置field的html属性呢?


在Django中无论何种field,都有一个widget的属性:

1 class Field(object):
2     widget = TextInput  # Default widget to use when rendering this type of Field.
3     hidden_widget = HiddenInput  # Default widget to use when rendering this as "hidden".

如上所示,widget默认是TextInput。

而TextInput是一个继承Input的一个类:

1 class TextInput(Input):
2     input_type = 'text'
3 
4     def __init__(self, attrs=None):
5         if attrs is not None:
6             self.input_type = attrs.pop('type', self.input_type)
7         super(TextInput, self).__init__(attrs)

往上接着找,Input继承于Widget,不同于Widget的是它有个input_type。当继承Input时需要指明input_type,像上面的TextInput一样指明为'text',类似的,PasswordInput则将其指明为'password'。

 1 class Widget(six.with_metaclass(RenameWidgetMethods)):
 2     needs_multipart_form = False  # Determines does this widget need multipart form
 3     is_localized = False
 4     is_required = False
 5     supports_microseconds = True
 6 
 7     def __init__(self, attrs=None):
 8         if attrs is not None:
 9             self.attrs = attrs.copy()
10         else:
11             self.attrs = {}

在Widget中有个attrs的属性,这个属性其实可以用来设置对应field的html属性。这个属性在Widget的render里会被引用。

所以如果你需要设置某个字段的html属性时,可以这么做:

1 field = forms.CharField()
2 field.widget.attrs['readonly']='true'

如果是一个这样的form:

from user.models import User
from django import forms

class RegisterForm(forms.ModelForm):
    
    class Meta:
        fields = ('first_name', 'last_name', 'email', 'username',)

你需要这样才能设置field的attrs:

for field in form:
    field.field.widget.attrs['readonly']='false'

为什么要这样呢?因为ModelForm的Field是一个BoundField:

 1 class BoundField(object):
 2     "A Field plus data"
 3     def __init__(self, form, field, name):
 4         self.form = form
 5         self.field = field
 6         self.name = name
 7         self.html_name = form.add_prefix(name)
 8         self.html_initial_name = form.add_initial_prefix(name)
 9         self.html_initial_id = form.add_initial_prefix(self.auto_id)
10         if self.field.label is None:
11             self.label = pretty_name(name)
12         else:
13             self.label = self.field.label
14         self.help_text = field.help_text or ''
15         self._initial_value = UNSET

BoundField不像CharField或其他一般的Field,并不是直接继承于Field。所以当你需要获得BoundField的Field的对象的时候,需要使用它的field的属性。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM