2016-04-22 66 views
0

以我脆弱的形式,我只想在其中一个输入字段中插入一个size =“3”,以便匹配其最大长度。我试图在将bpm定义为CharField时插入maxlength的插入方式,但它不起作用。django-crispy-forms如何在一个输入字段中插入大小选项?

目前呈现时,它显示

<input class="textinput textInput form-control" id="id_bpm" maxlength="3" name="bpm" type="text" /> 

但我想改变它显示

<input class="textinput textInput form-control" id="id_bpm" maxlength="3" size="3" name="bpm" type="text" /> 

在我的表格模板,我叫{%酥脆形式%}

在my forms.py:

from django import forms 
from .models import Profile, Artist 
from crispy_forms.helper import FormHelper 
from crispy_forms.layout import Submit, Layout, Div 
from crispy_forms.bootstrap import StrictButton, FormActions 

class ProfileForm(forms.ModelForm): 

    class Meta: 
     model = Profile 
     fields = [ 
      "artist", 
      "title", 
      "mix", 
      "bpm", 
      "genre", 
      ] 

    artist = forms.CharField(widget=forms.TextInput)   
    bpm = forms.CharField(widget=forms.TextInput, max_length=3) 

    def __init__(self, *args, **kwargs): 
     super(ProfileForm, self).__init__(*args, **kwargs) 
     self.helper = FormHelper() 
     self.helper.form_class = 'form-horizontal' 
     self.helper.label_class = 'col-lg-2' 
     self.helper.field_class = 'col-lg-10' 
     self.helper.layout = Layout(
      'artist', 
      'title', 
      'mix', 
      'bpm', 
      'genre', 
      FormActions(Div(Submit('submit','Submit', css_class='btn-primary'), style="float: right")), 
     ) 

    def clean_artist(self): 
     artist = self.cleaned_data.get("artist") 
     if not artist: 
      raise forms.ValidationError("Artist is a required field.") 
     else: 
      artist, created = Artist.objects.get_or_create(name=artist) 
      return artist 

回答

0

使用Field布局对象为您的布局对象指定任何attributes

from crispy_forms.layout import Field 

self.helper.layout = Layout(
    'artist', 
    'title', 
    'mix', 
    Field('bpm', size=3), 
    'genre', 
    # ... 
)