Django Crispy Form Submit Button

anderish picture anderish · Feb 19, 2017 · Viewed 8.1k times · Source

I am trying to use Crispy Forms to make my forms look good. I have the following in my forms.py:

from django import forms
from .models import Team
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
from crispy_forms.bootstrap import (
    PrependedText, PrependedAppendedText, FormActions)

class CreateTeamForm(forms.ModelForm):
    class Meta:
        model = Team

        fields = [ 'Project_name', 'Project_number'
                  ]

        helper = FormHelper()
        helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))

        helper.form_method = 'POST'

Then in my views.py:

def create_team(request):
    if request.method == 'POST':
        form = CreateTeamForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render('/teams/my_team.html',{''})
    else:
        form = CreateTeamForm()

    return render(request, 'teams/team_form.html', {'form':CreateTeamForm()})

And finally in my template:

{% extends "main/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="row">
        <div class="jumbotron">
            {% crispy form %}

        </div>
    </div>
{% endblock %}

However, my submit button that I called isn't being displayed. I have read the cripsy form documentation and I can't seem to find anything wrong with my implementation. Everything except for the submit button is displayed. Any ideas?

Answer

Chris picture Chris · Feb 19, 2017

Your FormHelper should be an attribute of your form class, not its Meta class. Outdent that part of your code:

class CreateTeamForm(forms.ModelForm):
    class Meta:
        model = Team

        fields = [ 'Project_name', 'Project_number' ]

    helper = FormHelper()
    helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))
    helper.form_method = 'POST'