### Install and Initialize Tailwind CSS
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Install Tailwind CSS and its peer dependencies, then initialize its configuration file.
```bash
# Install Tailwind CSS
npm install -D tailwindcss postcss autoprefixer
# Initialize config
npx tailwindcss init -p
```
--------------------------------
### Install crispy-tailwind Locally
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/contributing.txt
Install the package in editable mode after setting up the virtual environment and development requirements.
```bash
pip install -e .
```
--------------------------------
### Install crispy-tailwind via pip
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.txt
Install the package using pip. This is the first step to integrating crispy-tailwind into your project.
```bash
pip install crispy-tailwind
```
--------------------------------
### Install crispy-tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/README.rst
Install the package using pip. Ensure you add 'crispy_forms' and 'crispy_tailwind' to INSTALLED_APPS and set the template pack.
```python
pip install crispy-tailwind
```
```python
INSTALLED_APPS = (
...
"crispy_forms",
"crispy_tailwind",
...
)
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
```
--------------------------------
### Install Local crispy-tailwind in Test Project
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/contributing.txt
Install the local version of crispy-tailwind into the crispy-test-project. Ensure you provide the correct path to your local package.
```bash
pip install -e path/to/crispy-tailwind
```
--------------------------------
### Install and Configure Crispy-Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/01-overview.md
Add 'crispy_forms' and 'crispy_tailwind' to INSTALLED_APPS and configure CRISPY_ALLOWED_TEMPLATE_PACKS and CRISPY_TEMPLATE_PACK in your settings.py.
```python
INSTALLED_APPS = [
# ...
"crispy_forms",
"crispy_tailwind",
]
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
```
--------------------------------
### Django BaseFormSet Type Example
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Shows how to create a Django FormSet using formset_factory and instantiate it, resulting in a BaseFormSet object.
```python
from django.forms import formset_factory, Form, CharField
class MyForm(Form):
name = CharField()
MyFormSet = formset_factory(MyForm, extra=2)
formset = MyFormSet() # BaseFormSet instance
```
--------------------------------
### Django Context Type Example
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Demonstrates creating a Django Context object with form data, CSS container information, and the template pack setting.
```python
from django.template import Context
context = Context({
'form': my_form,
'css_container': my_css_container,
'template_pack': 'tailwind'
})
```
--------------------------------
### Import and Get Package Version
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Demonstrates how to import the crispy_tailwind package and access its version information.
```python
import crispy_tailwind
print(crispy_tailwind.__version__) # "1.0.3"
```
--------------------------------
### Create a Success Alert with Dismiss Button
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/02-api-reference-layout.md
This example shows how to create a success alert that includes a dismissible close button. Set `dismiss=True` to enable the close button, and customize styling with `css_class`.
```python
Alert(
content="Form submitted successfully!",
css_class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4",
dismiss=True
)
```
--------------------------------
### Django BoundField Type Example
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Illustrates the creation of a Django Form and accessing a BoundField instance, which represents a form field bound to data.
```python
from django.forms import Form, CharField
class MyForm(Form):
name = CharField()
form = MyForm(data={'name': 'John'})
bound_field = form['name'] # BoundField instance
```
--------------------------------
### Template Usage Examples for crispy_addon
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Demonstrates various ways to use the `crispy_addon` tag in Django templates for fields like price, distance, percentage, domain, and phone numbers.
```django
{% load tailwind_field %}
{# Price field with currency symbol #}
{% crispy_addon form.price prepend="$" %}
```
```django
{% load tailwind_field %}
{# Distance with unit #}
{% crispy_addon form.distance append=" km" %}
```
```django
{% load tailwind_field %}
{# Percentage field #}
{% crispy_addon form.percentage append="%" %}
```
```django
{% load tailwind_field %}
{# Domain with protocol #}
{% crispy_addon form.domain prepend="https://" %}
```
```django
{% load tailwind_field %}
{# Phone number with country code and formatting #}
{% crispy_addon form.phone prepend="+1 (" append=")" %}
```
--------------------------------
### Combining Row and Column Layouts
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/layout_objects.md
An example illustrating the typical usage of Row and Column layout objects together to create structured form layouts. This combination is effective for arranging fields in a responsive grid system.
```python
Row(
Column(Field("first_name"), Field("last_name"), css_class="px-2"),
Column("email", css_class="px-2"),
)
```
--------------------------------
### Customized Submit Button with Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/layout_objects.txt
Example of a customized Submit button using Tailwind CSS classes for styling. This allows for detailed control over the button's appearance.
```python
form.helper.layout = Layout(Submit("submit", "Submit", css_class="bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded"))
```
--------------------------------
### Create a Custom Styled Warning Alert
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/02-api-reference-layout.md
Use this example to create a warning alert with specific Tailwind CSS classes for styling. The `css_class` parameter controls the appearance of the alert container.
```python
Alert(
content="Warning! Passwords do not match.",
css_class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4"
)
```
--------------------------------
### Custom Base Input (Button) Template
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/10-template-system.md
Override the 'baseinput.html' template to customize the appearance of input elements, such as buttons. This example applies Tailwind classes for styling and handles disabled states.
```django
{% load tailwind_filters %}
```
--------------------------------
### Create a Django Form Field with Custom Widget
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Instantiate a `django.forms.Field` and associate it with a custom widget. This example creates a CharField with a TextInput widget that includes custom HTML attributes like class and placeholder.
```python
from django import forms
widget = forms.TextInput(attrs={'class': 'custom-class', 'placeholder': 'Enter text'})
field = forms.CharField(widget=widget)
```
--------------------------------
### Complete HTML Template for Contact Form
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/04-api-reference-filters.md
An example Django HTML template (`contact.html`) that loads the `tailwind_filters`, includes a CSRF token, renders the form using `{{ form|crispy }}`, and adds a submit button with Tailwind classes.
```django
{# contact.html #}
{% load tailwind_filters %}
Contact Us
```
--------------------------------
### Build and Serve Documentation
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/contributing.txt
Build the HTML documentation and serve it locally to review changes. Navigate to the docs directory first.
```bash
cd docs && make html
cd _build/html && python -m http.server
```
--------------------------------
### Import and Initialize CSSContainer
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/custom.txt
Import CSSContainer from crispy_tailwind.tailwind and initialize it with a dictionary of widget-class styles.
```python
from crispy_tailwind.tailwind import CSSContainer
css = CSSContainer({
"text": "border border-gray-300",
"number": "border border-gray-300",
...
})
```
--------------------------------
### Use crispy_addon with Only Append
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.md
This example demonstrates using 'crispy_addon' to add only an appended value to a form field.
```default
{% load tailwind_field %}
{% crispy_addon form.my_field append=".00" %}
```
--------------------------------
### Use crispy_addon with Only Prepend
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.md
This example shows how to use 'crispy_addon' to add only a prepended value to a form field.
```default
{% load tailwind_field %}
{% crispy_addon form.my_field prepend="$" %}
```
--------------------------------
### Django Form Definition
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/04-api-reference-filters.md
Defines a simple Django `ContactForm` with fields for name, email, and message. This form is used in the template rendering examples.
```python
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label="Your Name")
email = forms.EmailField(label="Email Address")
message = forms.CharField(widget=forms.Textarea, label="Message")
```
--------------------------------
### Configure Django INSTALLED_APPS
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.md
Add 'crispy_forms' and 'crispy_tailwind' to your project's INSTALLED_APPS setting to enable the packages.
```default
INSTALLED_APPS = (
...
"crispy_forms",
"crispy_tailwind",
...
)
```
--------------------------------
### Django View for Contact Form
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/08-usage-examples.md
A Django view to handle the contact form submission. It processes POST requests and renders the form for GET requests.
```python
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form
name = form.cleaned_data['name']
email = form.cleaned_data['email']
# Send email, save to database, etc.
return render(request, 'contact_success.html')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
```
--------------------------------
### Load Formset Template
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/10-template-system.md
Demonstrates how to use the `uni_formset_template` function to load the cached template for formset rendering. Caching improves performance.
```python
from crispy_tailwind.templatetags.tailwind_filters import uni_formset_template
template = uni_formset_template('tailwind')
# Returns: Template object for tailwind/uni_formset.html
```
--------------------------------
### Package Structure
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Illustrates the directory and file layout of the crispy-tailwind package.
```tree
crispy_tailwind/
├── __init__.py # Package initialization (__version__)
├── layout.py # Submit, Reset, Button, Alert classes
├── tailwind.py # CSSContainer class
└── templatetags/
├── __init__.py # Package initialization
├── tailwind_filters.py # Form rendering filters
└── tailwind_field.py # Field rendering and tag definitions
```
--------------------------------
### Tailwind Field Template Tag Syntax
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Provides examples of the `tailwind_field` and `crispy_addon` template tag syntax, including passing custom attributes to `tailwind_field`.
```django
{% load tailwind_field %}
{% tailwind_field form.field %}
{% tailwind_field form.field attr1="value1" attr2="value2" %}
{% crispy_addon form.field prepend="$" %}
```
--------------------------------
### CSSContainer Initialization with Base Styles
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Initializes a CSSContainer with base styles that apply to all default widget types. Widget-specific styles are then merged with these base styles.
```python
container = CSSContainer({"base": "p-2 text-gray-700"})
print(repr(container))
```
--------------------------------
### Handle FormSet in Django View
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/08-usage-examples.md
Processes POST requests for a formset and renders the formset in a template for GET requests. This view logic handles form submission and display.
```python
from django.shortcuts import render
def book_list(request):
if request.method == 'POST':
formset = BookFormSet(request.POST)
if formset.is_valid():
# Process formset
for form in formset.forms:
if form.cleaned_data:
# Save book
pass
return render(request, 'success.html')
else:
formset = BookFormSet()
return render(request, 'books.html', {'formset': formset})
```
--------------------------------
### Generated Documentation Files
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Lists the files generated for the API documentation, including their purpose and size.
```text
00-index.md (12 KB) - Navigation and quick reference
01-overview.md (2.5 KB) - Project overview
02-api-reference-layout.md (8.0 KB) - Layout objects API
03-api-reference-tailwind.md (7.0 KB) - CSSContainer API
04-api-reference-filters.md (11 KB) - Template filters API
05-api-reference-field-tag.md (11 KB) - Field rendering API
06-configuration.md (9.5 KB) - Configuration reference
07-types.md (8.9 KB) - Type definitions
08-usage-examples.md (16 KB) - 9 code examples
09-module-reference.md (12 KB) - Module structure
10-template-system.md (13 KB) - Template system reference
README.md (this file)
```
--------------------------------
### Run Test Suite
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/contributing.txt
Execute the test suite locally using pytest with the specified Django settings.
```bash
pytest --ds=tests.test_settings
```
--------------------------------
### Define a Django Form
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Use `django.forms.Form` as the base class for creating custom forms. This example shows how to define a simple contact form with name and email fields.
```python
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
form = ContactForm()
```
--------------------------------
### Display Form Errors at Top of Form
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/04-api-reference-filters.md
This example shows how to conditionally display non-field errors in a danger alert div before rendering the rest of the form using `|crispy`.
```django
{% load tailwind_filters %}
```
--------------------------------
### Create a Form with Submit Button
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/02-api-reference-layout.md
Use the `Submit` layout object within a `FormHelper` to define a form with a submit button. The first argument to `Submit` is the button's name/id, and the second is its label. The `{% crispy %}` tag renders the form.
```python
from crispy_forms.layout import Layout
from crispy_forms.helper import FormHelper
from crispy_tailwind.layout import Submit
class MyForm(forms.Form):
name = forms.CharField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'name',
Submit('search', 'Search the Site')
)
# In template:
# {% load crispy_forms_tags %}
# {% crispy form %}
```
--------------------------------
### Custom Alert Template
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/10-template-system.md
Customize the rendering of alert messages by overriding the 'alert.html' template. This example applies Tailwind CSS classes for styling and includes an optional dismiss button.
```django
{{ alert.content|safe }}
{% if alert.dismiss %}
{% endif %}
```
--------------------------------
### Initialize CSSContainer with Widget Styles
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/custom.md
Import and initialize `CSSContainer` by passing a dictionary of Django widget types to CSS class mappings. This sets the initial styles for specific input types.
```python
>>> from crispy_tailwind.tailwind import CSSContainer
>>> css = CSSContainer({
"text": "border border-gray-300",
"number": "border border-gray-300",
...
})
```
--------------------------------
### Load Form Template
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/10-template-system.md
Shows how to use the `uni_form_template` function to load the cached template for individual form rendering. Caching is utilized for efficiency.
```python
from crispy_tailwind.templatetags.tailwind_filters import uni_form_template
template = uni_form_template('tailwind')
# Returns: Template object for tailwind/uni_form.html
```
--------------------------------
### CSSContainer Initialization
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Initializes a CSSContainer instance with a dictionary of Tailwind CSS class strings. The 'base' key applies to all widget types, and specific keys override or merge with base styles.
```APIDOC
## Class: `CSSContainer`
Manages Tailwind CSS classes for different widget types. Supports base styles that apply to all widgets and widget-specific overrides. Supports addition and subtraction of class sets.
### Signature
```python
class CSSContainer:
def __init__(self, css_styles)
```
### Constructor Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `css_styles` | dict | Yes | — | Dictionary mapping widget/field names to Tailwind CSS class strings. Special key "base" applies to all default items. |
### Returns
`CSSContainer` instance with attributes for each widget type containing the composed CSS class strings.
```
--------------------------------
### Complete Form Rendering with tailwind_field
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Example of rendering a complete HTML form using the tailwind_field tag for each form field, including custom styling for message and layout for other fields.
```django
{% load tailwind_field %}
```
--------------------------------
### Tag-Based Form Rendering with Crispy-Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/00-index.md
For more control, use the `FormHelper` and `Layout` objects with the `crispy` tag. Ensure `crispy_forms_tags` is loaded.
```python
form.helper = FormHelper()
form.helper.layout = Layout('field1', 'field2', Submit('submit', 'Submit'))
```
```django
{% load crispy_forms_tags %}
{% crispy form %}
```
--------------------------------
### Define Django Form and FormSet
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/08-usage-examples.md
Defines a Django form for books and creates a formset factory for multiple book entries. This is the backend setup for handling multiple related forms.
```python
from django import forms
from django.forms import formset_factory
class BookForm(forms.Form):
title = forms.CharField(label="Book Title", max_length=200)
author = forms.CharField(label="Author", max_length=100)
isbn = forms.CharField(label="ISBN", max_length=20, required=False)
published_date = forms.DateField(label="Published Date", required=False)
BookFormSet = formset_factory(BookForm, extra=3)
```
--------------------------------
### Getting Input Class for a Field
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Extracts the CSS classes for a given Django form field based on its widget type. Returns an empty string if the widget type is not found in the container.
```python
from django import forms
from crispy_tailwind.tailwind import CSSContainer
class MyForm(forms.Form):
name = forms.CharField(widget=forms.TextInput())
form = MyForm()
container = CSSContainer({
"text": "bg-white border border-gray-300 p-2 rounded"
})
classes = container.get_input_class(form['name'])
```
--------------------------------
### Create a Button with JavaScript Action
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/02-api-reference-layout.md
Instantiate a Button object with specific Tailwind CSS classes and an `onclick` attribute to trigger a JavaScript function when clicked.
```python
Button(
'action',
'Click Me',
css_class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded",
onclick="doSomething()"
)
```
--------------------------------
### Python Import Usage
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Shows how to import specific components from the `tailwind_field` module for use in Python code.
```APIDOC
## Import Usage (Python)
```python
from crispy_tailwind.templatetags.tailwind_field import (
CrispyTailwindFieldNode,
is_checkbox,
css_class,
crispy_addon
)
```
```
--------------------------------
### Get Widget's CSS Class Name
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Returns the widget's class name in lowercase. Load the 'tailwind_field' template tags before use. This can be useful for identifying the type of widget being rendered.
```python
@register.filter
def css_class(field) -> str:
pass
```
```django
{% load tailwind_field %}
Widget type: {{ form.email|css_class }}
{# Output: "textinput" #}
```
--------------------------------
### Control Form Layout with FormHelper and Layout
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Utilize `FormHelper` and `Layout` objects to precisely control the arrangement of form fields, including grouping fields into rows and adding submit buttons.
```python
form.helper = FormHelper()
form.helper.layout = Layout(
Row(Column('first_name'), Column('last_name')),
'email',
Submit('submit', 'Submit')
)
```
--------------------------------
### Configure FormHelper with Tailwind CSS
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/07-types.md
Use FormHelper to configure form rendering, including setting the HTTP method, layout, and Tailwind-specific CSS containers. This is passed to the {% crispy %} template tag.
```python
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
from crispy_tailwind.tailwind import CSSContainer
class MyForm(forms.Form):
name = forms.CharField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout('name', Submit('submit', 'Submit'))
self.helper.css_container = CSSContainer({'base': 'p-2'})
```
--------------------------------
### Define a Django Form with Reset Button
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/02-api-reference-layout.md
Use the Reset class within a crispy-forms Layout to add a reset button to your form. This example shows how to integrate it with other form fields and a submit button.
```python
from crispy_forms.layout import Layout, ButtonHolder
from crispy_forms.helper import FormHelper
from crispy_tailwind.layout import Reset, Submit
from django import forms
class MyForm(forms.Form):
email = forms.EmailField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
'email',
ButtonHolder(
Submit('submit', 'Submit'),
Reset('reset', 'Clear Form')
)
)
```
--------------------------------
### Get CSS Classes from Field Widget Attributes
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Retrieves the CSS class string from a field's widget attributes. Returns None if no classes are present. Load the 'tailwind_field' template tags before use.
```python
@register.filter
def classes(field) -> str | None:
pass
```
```django
{% load tailwind_field %}
{% if form.name|classes %}
Current classes: {{ form.name|classes }}
{% endif %}
```
--------------------------------
### Import Tailwind Field Components in Python
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Shows how to import specific template tag and filter components from the `tailwind_field` module into your Python code.
```python
from crispy_tailwind.templatetags.tailwind_field import (
CrispyTailwindFieldNode,
is_checkbox,
css_class,
crispy_addon
)
```
--------------------------------
### crispy_tailwind Package Initialization
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
The root initialization module for the crispy-tailwind package. It exports the package version.
```APIDOC
## Module: `crispy_tailwind`
**Package root initialization module.**
### File Location
`crispy_tailwind/__init__.py`
### Exported Symbols
| Name | Type | Description |
|------|------|-------------|
| `__version__` | str | Package version (1.0.3) |
### Import Usage
```python
import crispy_tailwind
print(crispy_tailwind.__version__) # "1.0.3"
```
```
--------------------------------
### Iterating and Including Input Layout
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/crispy_tailwind/templates/tailwind/inputs.html
This snippet iterates over a list of 'inputs' and includes a base input layout template for each. It conditionally renders based on the presence of 'inputs' and 'label_class'.
```html
{% if inputs %}
{% if label_class %}
{% endif %}
{% for input in inputs %} {% include "tailwind/layout/baseinput.html" %} {% endfor %}
{% endif %}
```
--------------------------------
### Layout Objects for Form Rendering
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Shows how to import and use layout objects like Submit, Reset, Button, and Alert for form rendering with Tailwind CSS styling. This is useful for defining the structure and interactive elements of your forms.
```python
from crispy_tailwind.layout import Submit, Reset, Button, Alert
from crispy_forms.layout import Layout, ButtonHolder
layout = Layout(
'field_name',
ButtonHolder(
Submit('submit', 'Submit'),
Reset('reset', 'Reset'),
Button('cancel', 'Cancel')
),
Alert(content="Important message")
)
```
--------------------------------
### Prepare Context for Dynamic Template Styling
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Create a Django `Context` object that includes a form instance and a `CSSContainer` instance. This allows Tailwind styles to be dynamically applied within templates.
```python
from django.template import Context
form = MyForm()
container = CSSContainer({
"text": "p-2 border",
"error_border": "border-red-500"
})
context = Context({
"form": form,
"css_container": container
})
```
--------------------------------
### Individual Field Rendering with Custom Classes
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/04-api-reference-filters.md
Renders multiple form fields within a custom layout, applying specific Tailwind CSS classes to labels and field containers for styling. This example shows how to style first name, last name, and email fields individually.
```django
{% load tailwind_filters %}
```
--------------------------------
### Multi-Step Form View Logic
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/08-usage-examples.md
Handles the logic for a multi-step form, including managing form display, data validation, session storage, and navigation between steps. It redirects to the next step upon successful submission or to a success page upon completion.
```python
from django.shortcuts import render, redirect
from django.contrib.sessions.models import Session
def multi_step_form(request, step=1):
if step not in [1, 2, 3]:
step = 1
# Retrieve session data
session_data = request.session.get('form_data', {})
if step == 1:
form_class = Step1Form
elif step == 2:
form_class = Step2Form
else:
form_class = Step3Form
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
# Save data to session
session_data.update(form.cleaned_data)
request.session['form_data'] = session_data
if step < 3:
return redirect('multi_step_form', step=step+1)
else:
# Process final form
return redirect('success')
else:
# Pre-fill with session data if available
form = form_class(initial=session_data)
return render(request, 'multi_step.html', {
'form': form,
'step': step,
'total_steps': 3
})
```
--------------------------------
### Configure Django Settings for Crispy Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Add 'crispy_forms' and 'crispy_tailwind' to INSTALLED_APPS and set CRISPY_TEMPLATE_PACK to 'tailwind'. This enables the Tailwind template pack for django-crispy-forms.
```python
# settings.py
INSTALLED_APPS = [
'crispy_forms',
'crispy_tailwind',
]
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
```
--------------------------------
### Initialize CSSContainer with Base Styles
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Use `CSSContainer` to define base Tailwind classes that apply to all widgets. This is useful for setting consistent styling like borders, padding, and width.
```python
from crispy_tailwind.tailwind import CSSContainer
base_styles = {
"base": "bg-white focus:outline-none border border-gray-300 rounded-lg py-2 px-4 block w-full"
}
container = CSSContainer(base_styles)
# All widget types now have the base classes
```
--------------------------------
### Load and Use Tailwind Field Tags
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Demonstrates how to load the `tailwind_field` template tags and use `tailwind_field` and `crispy_addon` for rendering form fields and adding prepended/appended text.
```django
{% load tailwind_field %}
{% tailwind_field form.field %}
{% crispy_addon form.field prepend="$" %}
{{ form.field|is_checkbox }}
{{ form.field|css_class }}
```
--------------------------------
### Minimal CSS Container Styling
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Apply basic padding and border styling to form elements using the CSSContainer helper.
```python
CSSContainer({
'base': 'p-2 border rounded'
})
```
--------------------------------
### Import and Use Tailwind Filters in Python
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Import and directly call template filter functions like `as_crispy_form` and `as_crispy_field` from `tailwind_filters` for programmatic form rendering.
```python
from crispy_tailwind.templatetags.tailwind_filters import as_crispy_form, as_crispy_field
# Direct function calls (normally called via templates)
html = as_crispy_form(form)
field_html = as_crispy_field(bound_field)
```
--------------------------------
### API Reference: Layout Objects
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Documentation for Layout objects including Submit, Reset, Button, and Alert classes. This section details the API for 4 classes used in form layouts.
```APIDOC
## API Reference: Layout Objects
This section details the API for the following layout objects:
- Submit
- Reset
- Button
- Alert
### Scope
Covers 4 classes with complete API documentation.
```
--------------------------------
### Configure Django Settings for Crispy Forms and Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.txt
Update your project's settings to include 'crispy_forms' and 'crispy_tailwind' in INSTALLED_APPS. Set 'tailwind' as the allowed and default template pack.
```python
INSTALLED_APPS = (
...
"crispy_forms",
"crispy_tailwind",
...
)
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
```
--------------------------------
### Apply Base Styles with CSSContainer
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/custom.md
Use the 'base' key in the `CSSContainer` dictionary to apply a common set of CSS classes to all widgets. This is useful for setting default styles like background color.
```python
>>> css = CSSContainer({
"base": "bg-white"
})
>>> css
{
'text': 'bg-white',
'number': 'bg-white',
'email': 'bg-white',
...
}
```
--------------------------------
### Load Crispy Forms Utilities and Render Whole Form
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/crispy_tailwind/templates/tailwind/whole_uni_form.html
This snippet demonstrates the basic structure for rendering a complete Django form using Tailwind CSS. It loads necessary utilities, handles CSRF tokens for POST requests, and includes templates for displaying the form and its inputs.
```django
{% load crispy_forms_utils %} {% specialspaceless %} {% if form_tag %} {% endif %} {% if form_method|lower == 'post' and not disable_csrf %} {% csrf_token %} {% endif %} {% include "tailwind/display_form.html" %} {% include "tailwind/inputs.html" %} {% if form_tag %} {% endif %} {% endspecialspaceless %}
```
--------------------------------
### Iterate and Render Formset Forms and Fields
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/crispy_tailwind/templates/tailwind/table_inline_formset.html
Loops through each form in the formset and then through each field within that form, rendering them using the 'tailwind/field.html' partial with specific table cell styling.
```html
{% for form in formset %}
{% if form_show_errors and not form.is_extra %}
{% include "tailwind/errors.html" %}
{% endif %}
{% for field in form %}
{% include 'tailwind/field.html' with tag="td" form_show_labels=False field_class="border px-4 py-2" %}
{% endfor %}
{% endfor %}
```
--------------------------------
### Template Tag Usage
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/09-module-reference.md
Demonstrates how to load and use the `tailwind_field` and `crispy_addon` template tags within Django templates.
```APIDOC
## Template Tag Syntax
```django
{% load tailwind_field %}
{% tailwind_field form.field %}
{% tailwind_field form.field attr1="value1" attr2="value2" %}
{% crispy_addon form.field prepend="$" %}
```
```
--------------------------------
### Complete Form with Addon Fields
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Shows a complete HTML form structure using `crispy_addon` for shipping information fields, including price, weight, and distance.
```django
{% load tailwind_field %}
```
--------------------------------
### Include Inputs Template
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/crispy_tailwind/templates/tailwind/table_inline_formset.html
Includes a partial template for rendering input elements, likely containing common input field structures.
```html
{% include "tailwind/inputs.html" %}
```
--------------------------------
### Filter Rendering Flow
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/10-template-system.md
Illustrates the process when using the `crispy` filter on a form, showing how context data is created and templates are loaded.
```text
{{ form|crispy }}
↓
as_crispy_form() function
↓
Creates Context with form data
↓
Loads uni_form.html template
↓
Renders all fields through field.html
↓
Returns HTML string
```
--------------------------------
### Form Rendering with Custom Classes
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/04-api-reference-filters.md
Shows how to apply custom Tailwind CSS classes for labels and field containers directly within the `|crispy` filter. This allows for fine-grained styling control.
```django
{% load tailwind_filters %}
{# Custom styling #}
{{ form|crispy:label_class="text-lg font-semibold",field_class="mb-4 p-2" }}
```
--------------------------------
### API Reference: CSS Class Management
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Documentation for the CSS class management features, focusing on the CSSContainer class and its associated methods.
```APIDOC
## API Reference: CSS Class Management
This section details the API for CSS class management within crispy-tailwind.
### Scope
Focuses on the `CSSContainer` class and all its methods.
```
--------------------------------
### Use 'crispy_addon' Tag with Prepend Only
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/docs/getting_started.txt
Render a form field with only prepended text using the 'crispy_addon' tag.
```django
{% crispy_addon form.my_field prepend="$" %}
```
--------------------------------
### CSSContainer.__repr__()
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/03-api-reference-tailwind.md
Returns a string representation of the CSSContainer's internal dictionary, showing the currently applied CSS classes for each widget type.
```APIDOC
#### `__repr__()`
Returns string representation of the container's internal dictionary.
```python
container = CSSContainer({"base": "p-2 text-gray-700"})
print(repr(container))
# Output: {'text': 'p-2 text-gray-700', 'email': 'p-2 text-gray-700', ...}
```
```
--------------------------------
### API Reference: Field Rendering
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/README.md
Documentation related to rendering individual form fields using crispy-tailwind, including node classes, tags, and filters.
```APIDOC
## API Reference: Field Rendering
This section covers the API for rendering individual form fields with crispy-tailwind.
### Components
- 1 node class
- 1 tag
- 1 simple tag
- 8 filters
### Scope
Details the components involved in field rendering.
```
--------------------------------
### Override Default Templates
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Create a 'tailwind' directory within your project's 'templates' directory to override default templates. This allows for custom styling and layout.
```text
templates/
└── tailwind/
├── field.html
├── layout/
│ ├── button.html
│ ├── alert.html
│ └── ...
└── ...
```
--------------------------------
### Customize Widget Styling via Custom CSS Class Converter
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Define custom CSS class converters in `settings.py` and create corresponding Python classes to apply unique styling to specific widgets.
```python
# settings.py
CRISPY_CLASS_CONVERTERS = {
'customtextinput': 'custom_text_input',
}
# forms.py
class CustomTextInput(forms.TextInput):
pass
class MyForm(forms.Form):
special_field = forms.CharField(widget=CustomTextInput())
```
--------------------------------
### Bootstrap-Style Form CSS Container Styling
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Apply Bootstrap-like form element styling, including base classes and error border highlighting.
```python
CSSContainer({
'base': (
'form-control w-full px-3 py-2 border border-gray-300 '
'rounded focus:border-blue-500 focus:shadow-outline'
),
'error_border': 'border-red-500',
})
```
--------------------------------
### Required Django Settings for Crispy Tailwind
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/06-configuration.md
Ensure 'crispy_forms' and 'crispy_tailwind' are in INSTALLED_APPS and set CRISPY_ALLOWED_TEMPLATE_PACKS and CRISPY_TEMPLATE_PACK to 'tailwind'.
```python
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
# ...
'crispy_forms',
'crispy_tailwind', # Must come after crispy_forms
# ...
]
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
```
--------------------------------
### Invoice Form Template Usage
Source: https://github.com/django-crispy-forms/crispy-tailwind/blob/main/_autodocs/05-api-reference-field-tag.md
Renders an invoice form using `crispy_addon` to prepend currency and append percentage symbols to the respective fields.
```django
{% load tailwind_field %}
```