How to Integrate Semanti UI with Django and Crispy Forms

This post explains how to integrate Semantic UI with Django's Crispy Forms. After a lot of troubleshooting, it started working. It should be possible to improve parts of this process in the future, but it works for now.

Step 1

Install Crispy Forms. See the docs for instructions.

Step 2

I downloaded this code from Github. Save it in templates/semantic-ui/.

Step 3

Put this code in settings.py:

  1. CRISPY_TEMPLATE_PACK = 'semantic-ui'
  2. CRISPY_ALLOWED_TEMPLATE_PACKS = ('semantic-ui')

Step 4

Create a form in one of your Django apps. The example below is modified from the Crispy Forms docs.

  1. from django import forms
  2. from crispy_forms.helper import FormHelper
  3. from crispy_forms.layout import Submit
  4.  
  5.  
  6. class ExampleForm(forms.Form):
  7.  
  8. def __init__(self, *args, **kwargs):
  9. super(ExampleForm, self).__init__(*args, **kwargs)
  10. self.helper = FormHelper()
  11. self.helper.form_id = 'someId'
  12. self.helper.form_class = 'some-class'
  13. self.helper.form_method = 'post'
  14. self.helper.form_action = 'sample_form_name'
  15.  
  16. # Note that the submit button is added separately, with a Semantic UI class.
  17. self.helper.add_input(Submit('submit', 'Submit',
  18. css_class='ui button'))
  19.  
  20. like_website = forms.TypedChoiceField(
  21. label='Do you like this website?',
  22. choices=((1, 'Yes'), (0, 'No')),
  23. coerce=lambda x: bool(int(x)),
  24. widget=forms.RadioSelect,
  25. initial='1',
  26. required=True,
  27. )
  28.  
  29. favorite_food = forms.CharField(
  30. label='What is your favorite food?',
  31. max_length=80,
  32. required=True,
  33. )
  34.  
  35. favorite_color = forms.CharField(
  36. label='What is your favorite color?',
  37. max_length=80,
  38. required=True,
  39. )
  40.  
  41. favorite_number = forms.IntegerField(
  42. label='Favorite number',
  43. required=False,
  44. )
  45.  
  46. notes = forms.CharField(
  47. label='Additional notes or feedback',
  48. required=False,
  49. )

Step 5

Update your view:

  1. def sample_form(request):
  2. context = {'form': ExampleForm}
  3.  
  4. return render(request, 'someform/someform_create.html', context)

Step 6

Put the form in a template:

  1. {% extends 'coreapp/layouts/main.html' %}
  2. {% load crispy_forms_tags %}
  3.  
  4. {% block content %}
  5. <div class="ui form">
  6. {% crispy form %}
  7. </div>
  8. {% endblock %}

All Done

If it doesn't work, or if you have suggestions for improvement, please comment below!

Tue, 2017-11-07 05:22
Offline
Joined: 1 week 5 days ago

Semantic UI with Django


This can now be done even more easily with Django Semantic UI Forms. It even includes layout capability.

Tue, 2017-11-07 17:18
Offline
Joined: 2 years 8 months ago

Great, thanks for the update.


Great, thanks for the update.