简体   繁体   中英

add an icon to django crispy form submit button

I am struggling with the Button on a crispy form. Instead of just the default button I would like to have an icon inside

The form I am currently using is like

class MyForm(forms.ModelForm):

helper = FormHelper()
helper.layout = Layout(
    Div(
        Div(PrependedText('source_text', '<span class="fa fa-user"></span>'), css_class='col-md-6'),
        Div(PrependedText('destination_text','<span class="fa fa-flag-checkered"></span>'), css_class='col-md-6'),
        css_class='row-fluid'),
    Div(
        Div(PrependedText('departure', '<span class="fa fa-clock-o"></span>'), css_class='col-md-3'),
        Div('departure_delta', css_class='col-md-2'),
        Div(Submit('submit', "Neue Fahrt starten", css_class="btn"), css_class="col-md2"),
        css_class='row-fluid'),
)
helper.form_show_labels = False
helper.form_id = 'id_travelshare'

class Meta:

    model = MyModel
    fields = ['source', 'source_text', 'destination',
              'destination_text', 'departure', 'departure_delta']

    widgets = {
        'source': forms.HiddenInput(),
        'destination': forms.HiddenInput(),
        'departure' : forms.DateTimeInput(attrs={'class':'datetimepicker'}),
    }

What I want is a button with an icon inside. I did not find an example for this. Maybe somebody has one.

Kind regads

Michael

To do this it's hard to use the built-in Submit layout item. Instead, it's best to just use a general layout.HTML item like this:

    self.helper.layout.append(
        layout.HTML('<button type="submit" class="btn btn-primary">'
                    '<span class="fas fa-plus"></span> Apply to change order'
                    '</button>'))

You can add a CSS class to your submit button and then specify a background-image for buttons with this class:

Submit('submit', "Neue Fahrt starten", css_class="btn icon-button")

# in your .css file:
.btn.icon-button {
    background-image: url(../../icons/button-arrow-right.png);
}

This worked perfectly for me:

PrependedText('price', '<span class="fas fa-lira-sign"></span>')

This seemed like the easiest method compared the above solutions which were also worthy :-)

I can live with an ordinary link and submit the form with JS. Now it looks like :

<a href="#" class="btn btn-primary">
        <i class="fa fa-plus" aria-hidden="true"></i>
        Hinzufuegen
</a>

Regards

Michael

You can use StrictButton to create a button element instead of an input and set type to 'submit'. Then you can put any html you want inside the button.

StrictButton('Neue Fahrt starten <i class="fa fa-pencil"></i>', type="submit", css_class="btn")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM