django-crispy-forms如何在一个输入字段中插入大小选项?

k4aesqcs  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(86)

在我的crispy表单中,我只想在一个输入字段中插入size=“3”,这样它就能匹配它的maxlength。我尝试插入size的方式与插入maxlength的方式一样,当定义bpm为CharField时,它没有起作用。
当前渲染时,它显示

<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" />


在我的表单模板中,我称{% crispy form %}
在我的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

0s0u357o

0s0u357o1#

使用Field布局对象指定布局对象的任何属性:

from crispy_forms.layout import Field

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

字符串

a64a0gku

a64a0gku2#

可能不是100%匹配的答案,但对我有用:使用行+列控制宽度

self.helper.layout = Layout(
    Row(Column("type", css_class="col-3"), Column("minutes_down", 
    css_class="col-3"), css_class="ml-0"),
    Row(Column("comments", css_class="col-6"), css_class="ml-0"),
....

字符串
或者试试:

Field("comments", css_class="form-control form-control-lg w-100")

相关问题