### Basic iommi Admin Setup
Source: https://context7_llms
Demonstrates the minimal setup for an iommi admin interface by subclassing `Admin` and including its URLs in the project's URL configuration. This provides a functional admin GUI out of the box.
```python
from django.urls import path, include
from iommi.admin import Admin
class MyAdmin(Admin):
pass
urlpatterns = [
# ...
path('iommi-admin/', include(MyAdmin.urls())),
]
```
--------------------------------
### Basic iommi Admin Interface Setup
Source: https://context7_llms
This code demonstrates the minimal setup required to integrate the iommi administration interface into a Django project. It involves creating a class that inherits from `Admin` and including its URLs in the project's `urlpatterns`.
```python
class MyAdmin(Admin):
class Meta:
pass
urlpatterns = [
path('iommi-admin/', include(MyAdmin.urls())),
]
```
--------------------------------
### Advanced Fragment Example
Source: https://context7_llms
Provides an advanced example of creating an iommi Fragment with nested children, attributes, and custom tags. It also shows the resulting HTML output.
```python
Fragment(
'foo',
tag='div',
children__bar=Fragment('bar'),
attrs__baz='quux',
)
```
```html
foobar
```
--------------------------------
### Install and Configure iommi in Django
Source: https://context7_llms
Details the steps to install iommi using pip, add it to Django's INSTALLED_APPS, and include its essential middleware in the MIDDLEWARE setting. It highlights the importance of iommi's middleware placement.
```python
INSTALLED_APPS = [
# [...]
'iommi',
]
MIDDLEWARE = [
# These three are optional, but highly recommended!
'iommi.live_edit.Middleware',
# [... Django middleware ...]
'iommi.sql_trace.Middleware',
'iommi.profiling.Middleware',
# [... your other middleware ...]
'iommi.middleware',
]
```
--------------------------------
### Simple iommi Table Example
Source: https://context7_llms
A basic example of creating an iommi Table directly from a Django model. This automatically generates a table with pagination and sorting capabilities.
```python
Table(
auto__model=Album,
page_size=10,
)
```
--------------------------------
### iommi Action Examples
Source: https://context7_llms
Provides examples of creating different types of actions in iommi, including basic links, links with icons, standard buttons, submit buttons, and primary submit buttons for forms. It also explains the default behavior for submit actions within form namespaces.
```python
# Link
example=Action(attrs__href='http://example.com'),
# Link with icon
edit=Action.icon('pencil-square', attrs__href="edit/"),
# Button
button=Action.button(display_name='Button title!'),
# A submit button
submit=Action.submit(display_name='Do this'),
# The primary submit button on a form.
primary=Action.primary()
```
--------------------------------
### iommi Debug URL Builder Configuration
Source: https://context7_llms
Provides examples for configuring the `IOMMI_DEBUG_URL_BUILDER` setting to customize how debug tools jump to code in different IDEs. Includes examples for PyCharm (default) and VSCode.
```python
# Default configuration (example for PyCharm):
# settings.IOMMI_DEBUG_URL_BUILDER = lambda filename, lineno: f'pycharm://open?file={filename}&line={lineno}'
# VSCode configuration:
IOMMI_DEBUG_URL_BUILDER = lambda filename, lineno: 'vscode://file/%s:' % (filename,) + ('' if lineno is None else "%d" % (lineno,))
```
--------------------------------
### Example HTML with iommi Path Attribute
Source: https://context7_llms
Shows an example of an HTML table cell with the `data-iommi-path` attribute, which is added when iommi debug mode is enabled.
```html
explicit value |
```
--------------------------------
### iommi Documentation and Examples
Source: https://context7_llms
Notes documentation improvements, including new pages for dev tools and styles, and support for auto__include.
```python
Documentation improvements, for example new pages for dev tools, and styles
Support auto__include=['pk']
```
--------------------------------
### Reverse Foreign Key Table Example
Source: https://context7_llms
Provides an example of how to handle reverse foreign key relationships in tables, likely related to displaying related objects.
```python
reverse_fk_table
```
--------------------------------
### Table Definition Example
Source: https://context7_llms
Demonstrates how to define a basic Table component with columns and meta options for sorting.
```python
class AlbumTable(Table):
name = Column()
artist = Column()
class Meta:
sortable = False
```
--------------------------------
### EditTable Initialization Example
Source: https://context7_llms
Demonstrates how to initialize an EditTable with a specific model and column configurations. It includes setting up include fields and a delete column.
```python
table = EditTable(
auto__model=Album,
columns__name__field__include=True,
columns__delete=EditColumn.delete(),
)
```
--------------------------------
### Standalone Album Query Example
Source: https://context7_llms
Demonstrates a simple iommi query for filtering albums by artist and year. It includes a Python class for the query and HTML templates for rendering the query form and results. The example also shows how to collect and render iommi assets.
```python
class AlbumQuery(Query):
artist = Filter.choice_queryset(choices=Artist.objects.all())
year = Filter.integer()
def albums(request):
query = AlbumQuery().bind(request=request)
dispatch = query.perform_dispatch()
if dispatch is not None:
return dispatch
return render(
request=request,
template_name='albums.html',
context={
'query': query,
'albums': query.get_q(),
},
)
```
```html
{{ query }}
{% for album in albums %}
- {{ album }}
{% endfor %}
```
```html
{% for asset in query.iommi_collected_assets.values %}
{{ asset }}
{% endfor %}
```
--------------------------------
### Fragment Attributes Example
Source: https://context7_llms
Shows how to configure attributes for a Fragment, specifically setting the background style for a Table's header tag.
```python
table = Table(
auto__model=Artist,
h_tag__attrs__style__background='blue',
)
```
--------------------------------
### Custom iommi Base Template Example
Source: https://context7_llms
This HTML snippet provides an example of a custom iommi base template that extends the default iommi template and includes custom content in specific blocks.
```html
{% extends "iommi/base.html" %}
{% block iommi_top %}
{% include "my_menu.html" %}
{% endblock %}
{% block iommi_bottom %}
{% include "my_footer.html" %}
{% endblock %}
```
--------------------------------
### iommi Menu Class Example
Source: https://context7_llms
Demonstrates the creation of a Menu object with nested MenuItem instances for navigation. It shows how to define menu items with specific URLs and default URL generation.
```python
menu = Menu(
sub_menu=dict(
root=MenuItem(url='/'),
albums=MenuItem(url='/albums/'),
# url defaults to // so we
# don't need to write /musicians/ here
musicians=MenuItem(),
),
)
```
--------------------------------
### Namespace Dispatching Example
Source: https://context7_llms
Demonstrates the namespace dispatch mechanism in iommi, inspired by Django's query syntax, allowing for powerful and simple exposure of function APIs. It shows how default values and nested namespaces are handled.
```python
from iommi.declarative.dispatch import dispatch
from iommi.declarative.namespace import EMPTY
@dispatch(
b__x=1, # these are default values. "b" here is implicitly
# defining a namespace with a member "x" set to 1
c__y=2,
)
def a(foo, b, c):
print('foo:', foo)
some_function(**b)
another_function(**c)
@dispatch(
d=EMPTY, # explicit namespace
)
def some_function(x, d):
print('x:', x)
another_function(**d)
def another_function(y=None, z=None):
if y:
print('y:', y)
if z:
print('z:', z)
# now to call a()!
a('q')
# output:
# foo: q
# x: 1
# y: 2
a('q', b__x=5)
# foo: q
# x: 5
# y: 2
a('q', b__d__z=5)
# foo: q
# x: 1
# z: 5
# y: 2
```
--------------------------------
### Page Composition Example
Source: https://context7_llms
Demonstrates how to compose a full page using iommi's Page class, combining different components like HTML tags, Tables, and Forms.
```python
class MyPage(Page):
title = html.h1('My page')
users = Table(auto__model=User)
create_user = Form.create(auto__model=User)
# Usage in urls.py:
# path('my_page/', MyPage().as_view())
```
--------------------------------
### iommi Fix Examples Project Scrape Code
Source: https://context7_llms
Corrects the code used for scraping examples in the examples project. This ensures that example code is accurately captured and presented.
```python
# Code scraping and example generation logic updated.
```
--------------------------------
### iommi Fix Examples Project Scrape Code
Source: https://context7_llms
Corrects the code used for scraping examples in the examples project. This ensures that example code is accurately captured and presented.
```python
# Code scraping and example generation logic updated.
```
--------------------------------
### Table HTML Rendering Example
Source: https://context7_llms
Illustrates the rendering of an iommi Table component within an HTML iframe, as shown in the documentation.
```html
▼ Hide result
```
--------------------------------
### Form Configuration with Attributes
Source: https://context7_llms
Demonstrates how to configure a Form, including setting attributes on fields. It shows both a direct attribute assignment and a more succinct way using a dictionary for attributes. The example illustrates how 'style' and 'class' attributes are handled specially.
```python
form = Form(
auto__model=Album,
fields__artist__attrs__foo='bar',
fields__name__attrs__class__bar=True,
fields__name__attrs__style__baz='qwe',
)
```
```python
form = Form(
auto__model=Album,
fields__artist__attrs__foo='bar',
fields__name__attrs=dict(
class__bar=True,
style__baz='qwe',
)
)
```
```html
```
```python
form = Form(
auto__model=Album,
fields__name__attrs__class__bar=
lambda request, **_: request.user.is_staff,
)
```
--------------------------------
### iommi Query Language Example
Source: https://context7_llms
Illustrates the syntax of the iommi query language for filtering data, showing how to combine conditions like album name and lyrics content.
```text
album=Paranoid AND lyrics:"have the power"
```
--------------------------------
### iommi Path Parameter Usage in View
Source: https://context7_llms
Shows how iommi makes URL path parameters available directly as keyword arguments within a view. This example uses a 'name' parameter to display a greeting.
```python
class MyPage(Page):
hello = html.div(
lambda name, **_: f'Hello {name}',
)
urlpatterns = [
path('
/', MyPage().as_view()),
]
```
--------------------------------
### EditColumn select Shortcut Example
Source: https://context7_llms
Shows how to enable a 'select' column in a table using the EditColumn.select shortcut for row selection and bulk operations.
```python
table = Table(
auto__model=Album,
columns__select__include=True,
bulk__actions__submit=Action.submit(post_handler=my_handler)
)
```
--------------------------------
### Show Columns Example
Source: https://context7_llms
Demonstrates how to control the visibility of columns in a table. The `include` parameter, a boolean, determines if a column is shown.
```python
include=True
```
--------------------------------
### Custom Render Value Example
Source: https://context7_llms
Demonstrates how to customize the rendering of a field's value, especially when errors occur. This example uses a sentinel value to replace the actual field value during rendering.
```python
sentinel = '!!custom!!'
form = Form(
fields__foo=Field(
initial='not sentinel value',
render_value=lambda form, field, value, **_: sentinel,
)
)
```
--------------------------------
### Edit Table Example
Source: https://context7_llms
Demonstrates how to create an editable table using iommi's EditTable component. It shows how to enable editing for specific columns and add a delete row feature.
```python
EditTable(
auto__model=Album,
page_size=10,
# Turn on the edit feature for the year column
columns__year__field__include=True,
# Turn on the delete row feature
columns__delete=EditColumn.delete(),
)
```
--------------------------------
### Table Column Formatting Example
Source: https://context7_llms
Illustrates how to customize the rendering of a table column in iommi using a lambda function. This example shows how to append text to the displayed value of a specific column.
```python
Table(
auto__model=Artist,
columns__name__cell__format=lambda value, **_: f'{value} !!!',
)
```
--------------------------------
### Asset CSS Shortcut
Source: https://context7_llms
Provides examples and defaults for creating CSS assets using the Asset.css shortcut. This includes linking external stylesheets and embedding inline CSS.
```python
Asset.css(
attrs__href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css',
attrs__integrity='sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh',
attrs__crossorigin='anonymous',
)
Asset.css('p { font-size: 18pt; }')
Defaults:
tag: link
attrs__rel: stylesheet
```
--------------------------------
### Group Rows Example
Source: https://context7_llms
Demonstrates how to group rows in a table. This functionality is typically configured via the `row_group` attribute.
```python
row_group
```
--------------------------------
### Reverse Many-to-Many Example
Source: https://context7_llms
Illustrates handling reverse many-to-many relationships within the table context.
```python
reverse_m2m
```
--------------------------------
### Include Attributes Example
Source: https://context7_llms
Shows how to include specific attribute names in a data model, supporting nested attributes with double underscores. This allows for precise control over data inclusion.
```python
['album', 'album__year']
```
--------------------------------
### Multiple iommi Components with Page
Source: https://context7_llms
Demonstrates how to group multiple iommi components (like Tables) within a single Page for automatic namespacing and efficient management. This example shows a view with both albums and tracks tables.
```python
def view_artist(request, artist_name):
artist = get_object_or_404(Artist, name=artist_name)
class MyPage(Page):
albums = Table(auto__rows=artist.albums.all())
tracks = Table(
auto__rows=Track.objects.filter(album__artist=artist),
columns__album__filter__include=True,
)
page = MyPage().bind(request=request)
dispatch = page.perform_dispatch()
if dispatch is not None:
return dispatch
return render(
request,
'view_artist3.html',
context={
'artist': artist,
'tracks': page.parts.tracks,
'albums': page.parts.albums,
}
)
```
--------------------------------
### Query Class Example
Source: https://context7_llms
Demonstrates how to declare a query language using the Query class in iommi. It shows defining filters for 'year' and 'name' and then using the query to filter a Django QuerySet.
```python
class AlbumQuery(Query):
year = Filter.integer()
name = Filter()
query_set = Album.objects.filter(
AlbumQuery().bind(request=request).get_q()
)
```
--------------------------------
### EditColumn run Shortcut Example
Source: https://context7_llms
Demonstrates using the 'run' shortcut for an EditColumn to create a clickable run icon in a table. The URL defaults to the object's absolute URL plus '/run/'.
```python
table = Table(
auto__model=Album,
columns__run=Column.run(),
)
```
--------------------------------
### MainMenu Declaration Example
Source: https://context7_llms
Illustrates the declaration of a MainMenu component with nested items, including icon and view associations. This is used for creating main navigation in web applications.
```python
menu_declaration = MainMenu(
items=dict(
artists=M(
icon='people',
view=artists_view,
),
albums=M(
icon='disc',
view=albums_view,
),
),
)
urlpatterns = menu_declaration.urlpatterns()
```
--------------------------------
### iommi `extra__redirect` Parameter Handling
Source: https://context7_llms
Fixes an issue where `extra__redirect` was not getting all parameters. This ensures that redirect parameters are correctly passed through.
```python
# Parameter passing for redirect functionality.
```
--------------------------------
### Integrating iommi Table into a Django FBV
Source: https://context7_llms
This example demonstrates how to replace a manual HTML table in a Django function-based view (FBV) with an iommi `Table`. It shows fetching data, creating an iommi `Table` instance, binding it to the request, and passing it to the template context.
```python
from django.shortcuts import render, get_object_or_404
from iommi import Table
from .models import Artist
def view_artist(request, artist_name):
artist = get_object_or_404(Artist, name=artist_name)
albums = Table(
auto__rows=artist.albums.all(),
).bind(request=request)
return render(
request,
'view_artist2.html',
context={
'artist': artist,
'albums': albums,
}
)
```
--------------------------------
### Column.download() Example
Source: https://context7_llms
Creates a clickable download icon for a table row. The URL defaults to the object's absolute URL plus '/download/'. This can be overridden using the cell__url option. The cell value defaults to the object's primary key.
```python
table = Table(
auto__model=Album,
columns__download=Column.download(),
)
```
--------------------------------
### Supply Custom Initial Value for Form Fields
Source: https://context7_llms
Demonstrates how to set initial values for form fields using static values or callables. It also explains that GET parameters in the request can automatically populate fields.
```python
from iommi import Form
form = Form(
auto__model=Album,
fields__name__initial='Paranoid',
fields__year__initial=lambda field, form, **_: 1970,
)
```
--------------------------------
### Run iommi Tests
Source: https://context7_llms
Provides commands to set up a virtual environment, activate it, and run tests for the iommi project. It also includes a command to test the documentation build.
```bash
make venv
source venv/bin/activate
make test
make test-docs
```
--------------------------------
### Column.run() Usage Example
Source: https://context7_llms
Demonstrates how to use Column.run() to create a clickable run icon in a table. The URL defaults to your_object.get_absolute_url() + 'run/', but can be overridden using cell__url.
```python
table = Table(
auto__model=Album,
columns__run=Column.run(),
)
```
--------------------------------
### Running Tests with Tox
Source: https://context7_llms
Provides commands for setting up a virtual environment, activating it, and running tests using `tox` for the project.
```bash
make venv
source venv/bin/activate
make test
make test-docs
```
--------------------------------
### Function-Based View with Overridden Page Parts
Source: https://context7_llms
Provides an example of a function-based Django view that renders an iommi Page with overridden parts, demonstrating how to integrate iommi with existing Django views.
```python
def index(request):
return IndexPage(parts__subtitle__children__child='Still rocking...')
```
--------------------------------
### iommi Double Underscore Syntax for Nesting
Source: https://context7_llms
Demonstrates the use of the double underscore `__` as a shorthand for deeply nested dictionary configurations in iommi, making complex setups more concise.
```python
table = Table(
auto__model=Model,
columns__name__filter__include=True,
columns__name__filter__field__label__attrs__class__special=True,
)
```
--------------------------------
### iommi CRUD and Authentication Views
Source: https://context7_llms
This section introduces new `crud_views()`, `login`, `logout`, and `create_password` functions, installable via `auth_views()`. It also includes fixes for crashes and label mapping, adds 'Vanilla CSS' framework support, and enables targeting of table ``.
```python
# New `crud_views()` function added
# New `login`, `logout`, and `create_password` views added. You can install them all with `auth_views()`
# Fixed a crash in `Form.delete()`
# Don't crash on label mapping missing
# Added "Vanilla CSS" CSS framework
# Make it possible to target the `` of a table with configuration
```
--------------------------------
### Registering a TimeField Factory
Source: https://context7_llms
Shows a simple example of registering a custom factory for a `TimeField` using `register_factory`. This tells iommi how to handle specific field types, in this case, aliasing it with the shortcut name 'time'.
```python
register_factory(
TimeField,
shortcut_name='time'
)
```
--------------------------------
### One-off CSS Customization
Source: https://context7_llms
Provides an example of applying a specific CSS style to an input field within a form that was automatically generated. This demonstrates iommi's approach to single-point customization without boilerplate.
```python
Form(
auto__model=Album,
fields__year__input__attrs__style__font='helvetica')
```
--------------------------------
### iommi Field Configuration Options
Source: https://context7_llms
This section outlines various configuration parameters for iommi fields, including attribute paths, HTML attributes, display names, editability, and more. It references related documentation and cookbook examples for deeper understanding.
```APIDOC
field_order:
Type: Union[int, str]
Description: Sets the order of columns. See the howto for an example.
References: after
assets:
Type: Namespace
Description: Namespace for assets.
References: assets
attr:
Type: str
Description: The attribute path to apply or get data from. Using 'foo__bar__baz' will result in instance.foo.bar.baz being set by the apply() function. Setting to None means no attribute is read or written by apply(). Defaults to same as name.
References: evaluated, attr
attrs:
Type: Attrs
Description: A dict containing any custom html attributes to be sent to the input__template.
References: evaluated, attributes
Cookbook: freetext-column
choice_display_name_formatter:
Type: Callable[..., str]
Description: Callback to obtain the display name for a choice. Default uses str(choice).
Default: lambda choice, **_: '%s' % choice
choice_id_formatter:
Type: Callable[..., str]
Description: Callback to obtain the string value for a choice's identity. Default uses str(choice).
Default: lambda choice, **_: '%s' % choice
choice_to_optgroup:
Type: Optional[Callable[..., Optional[str]]]
choices:
Type: Callable[..., List[Any]]
References: evaluated
Cookbook: dependent-fields2, dependent-fields
display_name:
Type: str
Description: The text in the HTML label tag. Default: capitalize(name).replace('_', ' ')
References: evaluated, name
editable:
Type: bool
Description: Is this field editable.
Default: True
References: evaluated
Cookbook: create-or-edit-forms, non-rendered-field, field-non-editable
empty_label:
Type: str
Default: ---
References: evaluated
endpoints:
Type: Namespace
Description: Namespace for endpoints.
References: endpoints
errors:
Type: Errors
Cookbook: field-hidden
extra:
Type: Dict[str, Any]
References: extra
extra_evaluated:
Type: Dict[str, Any]
References: extra
extra_params:
References: extra_params
group:
Type: str
References: evaluated, group
Cookbook: group-fields
help:
Type: Fragment
help_text:
Description: Help text is grabbed from the django model if specified and available.
include:
Type: bool
References: evaluated, include
Cookbook: field-reverse-m2m, include-exclude-fields, show-fields
initial:
Type: Any
Description: Initial value of the field.
References: evaluated
Cookbook: non-rendered-field, field-initial-value
input:
Type: Fragment
Cookbook: field-input-template
iommi_style:
Type: str
References: iommi_style
is_boolean:
Type: bool
Default: False
References: evaluated
is_list:
Type: bool
Description: Interpret request data as a list. Default: False
Default: False
is_valid:
Description: Validation function. Should return a tuple of (bool, reason_for_failure_if_bool_is_false) or raise ValidationError.
Example:
form = Form.create(
auto__model=Artist,
fields__name__is_valid=lambda parsed_data, **_: (parsed_data.startswith('H'), 'Must start with H!'),
)
Cookbook: validate-multiple-fields-together, custom-validator
label:
Type: Fragment
```
--------------------------------
### Adding `GET` Endpoints
Source: https://context7_llms
Shows how to add arbitrary `GET` endpoints to a `Part` using the `endpoints` namespace. Endpoints can return `HttpResponse`, `Part`, or other data types which are then JSON-encoded.
```python
page = Page(
parts__h1=html.h1('Hi!'),
endpoints__echo__func=lambda value, **_: value,
)
# This page will respond to "?/echo=foo" by returning a json response "foo".
```
--------------------------------
### iommi Form with Custom Submit Action
Source: https://context7_llms
This example extends the basic iommi `AlbumForm` by customizing the submit button's display name. It demonstrates how to configure actions, such as the submit button, directly within the `Meta` class, providing a clean way to manage form behavior.
```python
class AlbumForm(Form):
class Meta:
auto__model = Album
auto__include = ['name', 'artist']
actions__submit__display_name = 'Save'
```
--------------------------------
### Table of Plain Python Objects with Custom Formatting
Source: https://context7_llms
Illustrates how to create a table from a list of plain Python objects. It includes examples of custom cell formatting, calculating values not present in the object, and disabling sorting for calculated columns.
```python
class Foo(object):
def __init__(self, i):
self.a = i
self.b = 'foo %s' % (i % 3)
self.c = (i, 1, 2, 3, 4)
class FooTable(Table):
a = Column.number()
b = Column()
c = Column(
cell__format=lambda value, **_: value[-1],
)
sum_c = Column(
cell__value=lambda row, **_: sum(row.c),
sortable=False,
)
def plain_objs_view(request):
foos = [Foo(i) for i in range(4)]
return FooTable(rows=foos)
```
--------------------------------
### iommi Base Templates
Source: https://context7_llms
Includes iommi/base_bootstrap.html and iommi/base_semantic_ui.html in the package, which are used if no base.html is present, improving the out-of-the-box experience.
```html

Your first pick for a django power chord
```
--------------------------------
### Django URL Path Mapping with iommi Path Decoding
Source: https://context7_llms
Configures Django URL patterns to utilize iommi's path decoding. This example maps 'artist_name' and 'album_pk' from the URL to corresponding iommi decoded parameters, providing model instances directly.
```python
urlpatterns = [
path('//', MyPage().as_view()),
]
```
--------------------------------
### Filter Column Example
Source: https://context7_llms
Demonstrates how to configure filtering for a specific column. The `filter` attribute is of type `Namespace`.
```python
filter
```
--------------------------------
### Creating a Page with iommi
Source: https://context7_llms
Demonstrates how to define a Page in iommi, including adding HTML elements, plain text, nested Pages, Tables, and Django Templates. It shows how non-Part types are converted to Part-derived classes.
```python
class MyPage(Page):
# Using the html builder to create a tag safely
h1 = html.h1('Welcome!')
# If you write an HTML tag in here it will be
# treated as unsafe and escaped by Django like normal
body_text = 'Welcome to my iommi site...'
# You can nest Page objects!
some_other_page = MyOtherPage()
# Table and Form are Part types
my_table = Table(auto__model=Artist)
# Django template
other_stuff = Template('{{ foo }}
')
```
--------------------------------
### iommi Callback Keyword Arguments
Source: https://context7_llms
Advises on best practices for iommi callbacks, recommending the use of `**_` to accept arbitrary keyword arguments and prevent breaking changes.
```APIDOC
def my_callback(traversable, **_):
# Use **_ to accept any additional keyword arguments.
```
--------------------------------
### iommi Get SQL Debug Handling
Source: https://context7_llms
Fixes the default handling for `get_sql_debug`, ensuring it functions correctly.
```python
# Fixed default handling for get_sql_debug
```
--------------------------------
### Create Django Page with iommi Tables
Source: https://context7_llms
Defines a Django page using iommi's Page component, incorporating multiple tables for different models (Artist, Album) and configuring pagination. This example demonstrates composing various iommi components into a single web page.
```python
from iommi import Page, Table
from django.urls import path
from .models import Artist, Album
import html
class IndexPage(Page):
title = html.h1('Supernaut')
welcome_text = 'This is a discography of the best acts in music!'
artists = Table(auto__model=Artist, page_size=5)
albums = Table(
auto__model=Album,
page_size=5,
)
tracks = Table(auto__model=Album, page_size=5)
urlpatterns = [
path('', IndexPage().as_view()),
]
```
--------------------------------
### Understanding naming conventions in iommi
Source: https://context7_llms
Explains the different naming concepts in iommi: 'name', 'display_name', and 'iommi_path'. 'name' is primarily used for configuration within the code.
```python
class MyTable(Table):
foo = Column()
# The 'name' is "foo".
```
--------------------------------
### Query Defaults to Field Inclusion
Source: https://context7_llms
Changed so that Query defaults to having the Field included by default, simplifying query setup.
```python
Query.include_field = True
```
--------------------------------
### Action Shortcuts and Defaults
Source: https://context7_llms
Demonstrates various shortcuts for creating Action elements like buttons, delete actions, icons, and submit actions. It also outlines default attribute values for these shortcuts.
```APIDOC
Action.button:
Defaults:
tag: button
Action.delete:
Parent: Action.submit_
Action.icon:
Defaults:
extra__icon_attrs__class: Namespace()
extra__icon_attrs__style: Namespace()
Action.primary:
Parent: Action.submit_
Action.submit:
Parent: Action.button_
Defaults:
attrs__accesskey: s
attrs__name: lambda action, **_: action.own_target_marker()
display_name: Submit
```
--------------------------------
### Create a Page with Tables (Python)
Source: https://context7_llms
Demonstrates creating a Django page with multiple iommi tables, a header, and text. It utilizes iommi's `Page` and `Table` components for declarative UI construction.
```python
class IndexPage(Page):
title = html.h1('Supernaut')
welcome_text = 'This is a discography of the best acts in music!'
artists = Table(auto__model=Artist, page_size=5)
albums = Table(
auto__model=Album,
page_size=5,
)
tracks = Table(auto__model=Album, page_size=5)
urlpatterns = [
path('', IndexPage().as_view()),
]
```
--------------------------------
### iommi CSV Rendering
Source: https://context7_llms
A CSV rendering endpoint has been fixed and an example provided, facilitating the export of data in CSV format.
```python
# Fixed CSV rendering endpoint
# Added CSV rendering example
```
--------------------------------
### Custom iommi Base Classes Boilerplate
Source: https://context7_llms
Provides a boilerplate code example for defining custom base classes for iommi components like Page, Action, Field, Form, Table, etc. This is essential for production environments to integrate iommi with existing codebases and add product-specific shortcuts.
```python
import iommi
class Page(iommi.Page):
pass
class Action(iommi.Action):
pass
class Field(iommi.Field):
pass
class Form(iommi.Form):
class Meta:
member_class = Field
page_class = Page
action_class = Action
class Filter(iommi.Filter):
pass
class Query(iommi.Query):
class Meta:
member_class = Filter
form_class = Form
class Column(iommi.Column):
pass
class Table(iommi.Table):
class Meta:
member_class = Column
form_class = Form
query_class = Query
page_class = Page
action_class = Action
class EditColumn(iommi.EditColumn):
pass
class EditTable(iommi.EditTable):
class Meta:
member_class = EditColumn
form_class = Form
query_class = Query
page_class = Page
action_class = Action
class Menu(iommi.Menu):
pass
class MenuItem(iommi.MenuItem):
pass
```
--------------------------------
### Basic Styling Support
Source: https://context7_llms
Added basic styling support for the Water and Foundation CSS frameworks.
```python
Styling('water')
```
```python
Styling('foundation')
```
--------------------------------
### Customize Header Example
Source: https://context7_llms
Shows how to customize the table header. The `header` attribute is of type `Namespace` and allows for detailed header configuration.
```python
header
```
--------------------------------
### Declarative Form Initialization
Source: https://context7_llms
Demonstrates how to initialize a form declaratively by passing arguments to the constructor, which are then used to configure the form's behavior and appearance.
```python
AlbumForm(
auto__model=Album,
auto__include=['name', 'artist'],
actions__submit__display_name='Save',
)
```
--------------------------------
### Path Decoding with iommi
Source: https://context7_llms
Illustrates how to register path decoding components and define pages that dynamically fetch data based on URL parameters. Includes setting up tables with data filtered by these parameters.
```python
register_path_decoding(
artist_name=Artist.name,
)
class ArtistPage(Page):
title = html.h1(lambda artist, **_: artist.name)
albums = Table(
auto__model=Album,
rows=lambda artist, **_: Album.objects.filter(artist=artist),
)
tracks = Table(
auto__model=Track,
rows=lambda artist, **_: Track.objects.filter(album__artist=artist),
)
urlpatterns = [
path('artist//', ArtistPage().as_view()),
]
```
--------------------------------
### Creating HTML Fragments with iommi
Source: https://context7_llms
Demonstrates how to create HTML fragments using the Fragment class in iommi. It shows both direct instantiation and the use of the html builder shorthand. Fragments are configurable and can be modified after initial creation.
```python
h1 = Fragment(children__text='Tony', tag='h1')
# There is also a shorthand version that is identical to the above:
h1 = Fragment('Tony', tag='h1')
# Using the html builder:
h1 = html.h1('Tony')
# Example of configuring a fragment later:
class MyPage(Page):
header = html.h1(
'Hi!',
attrs__class__staff__=
lambda request, **_: request.user.is_staff,
)
# Rendering MyPage with a different tag:
MyPage(parts__header__tag='h2')
```
--------------------------------
### iommi Debug Menu Features
Source: https://context7_llms
Details the presence of the edit button in the debug menu (when middleware is installed) and the addition of a profile button.
```python
Edit button only present in debug menu when the edit middleware is installed
Added profile button to debug menu
```
--------------------------------
### Define and Register Custom Style
Source: https://context7_llms
Demonstrates how to create a custom style object and register it with iommi. This is typically done in an AppConfig's ready() method.
```python
from iommi.style import Style, register_style
# Define your custom style, potentially basing it on an existing one
my_style = Style(bootstrap)
# Register the style with a name
register_style('my_style', my_style)
```
--------------------------------
### Group Columns Example
Source: https://context7_llms
Illustrates how to group columns under a common header row. The `group` parameter defines the string describing the group, and consecutive identical groups are merged.
```python
group
```
--------------------------------
### iommi HTML Builder Usage
Source: https://context7_llms
Shows the basic usage of the iommi `html` builder object for creating HTML tags safely. It demonstrates creating an h1 tag and explains that it's equivalent to creating a Fragment instance.
```python
html.h1('some text')
```
--------------------------------
### Target Element by Shortcut Name
Source: https://context7_llms
Illustrates applying style definitions to specific component shortcuts, allowing for granular control over styling.
```python
Style(
MyClass__shortcuts__my_shortcut__attrs__class__foo=True,
)
```
--------------------------------
### iommi Programmatic Table Creation
Source: https://context7_llms
Illustrates the programmatic way to create an iommi Table with a specified model and columns.
```python
table = Table(
model=Album,
columns=dict(
name=Column(),
),
)
```
--------------------------------
### Column.edit() Example
Source: https://context7_llms
Creates a clickable edit icon for a table row. The URL defaults to the object's absolute URL plus '/edit/'. This can be overridden using the cell__url option.
```python
table = Table(
auto__model=Album,
columns__edit=Column.edit(after=0),
)
```
--------------------------------
### iommi `as_view` Lazy Refinement
Source: https://context7_llms
Makes `.as_view` lazy with `refine_done` to not explode import times. This optimization improves startup performance by deferring refinement until necessary.
```python
# Lazy evaluation of view rendering.
```
--------------------------------
### Column.delete() Example
Source: https://context7_llms
Creates a clickable delete icon for a table row. The URL defaults to the object's absolute URL plus '/delete/'. This can be overridden using the cell__url option.
```python
table = Table(
auto__model=Album,
columns__delete=Column.delete(),
)
```
--------------------------------
### Default Admin Theme
Source: https://context7_llms
Sets the default admin theme to Bootstrap.
```python
# Set admin to bootstrap by default.
```
--------------------------------
### Custom Table Actions
Source: https://context7_llms
Demonstrates how to define custom actions for table rows, allowing for interactive elements within the table interface. This example shows a link as a custom action.
```python
t = Table(
auto__model=Album,
columns__link=Column.link(attr=None, cell__url='/', cell__value='Link'),
)
```
--------------------------------
### Creating a Basic iommi Table
Source: https://context7_llms
This snippet shows how to define a basic iommi Table linked to a Django model (Album) and expose it as a view in your urls.py.
```python
from iommi import Table
from .models import Album
urlpatterns = [
path('iommi-table-test/', Table(auto__model=Album).as_view()),
]
```
--------------------------------
### HTML Fragment Builder
Source: https://context7_llms
Demonstrates the use of iommi's html fragment builder for creating simple HTML elements like h1 tags. Shows how to customize attributes like class.
```python
>>> class MyPage(Page):
... title = html.h1('Supernaut')
>>> MyPage().bind().__html__()
'Supernaut
'
>>> MyPage(parts__title__attrs__class__foo=True).bind().__html__()
'Supernaut
'
```
--------------------------------
### Exclude Attributes Example
Source: https://context7_llms
Demonstrates how to exclude specific attribute names from a data model, including nested attributes using double underscores. This is useful for controlling which fields are displayed or processed.
```python
['album', 'album__year']
```
--------------------------------
### Defining a Base Page with Standard Parts
Source: https://context7_llms
Illustrates the creation of a base Page class in iommi that includes standard parts like a title and subtitle. This serves as a foundation for other pages.
```python
class BasePage(Page):
title = html.h1('My awesome webpage')
subtitle = html.h2('It rocks')
```
--------------------------------
### iommi Field Validation Example
Source: https://context7_llms
Demonstrates how to implement a custom validation function for an iommi field. The `is_valid` parameter accepts a callable that returns a boolean and an error message, or raises a ValidationError.
```python
from iommi import Form
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
form = Form.create(
auto__model=Artist,
fields__name__is_valid=lambda parsed_data, **_: (parsed_data.startswith('H'), 'Must start with H!'),
)
```
--------------------------------
### Column.select() for Row Selection
Source: https://context7_llms
Shows how to use Column.select() to add checkboxes for row selection, typically used for bulk operations. It includes an example of a custom post handler for selected rows.
```python
def my_handler(table):
rows = table.selection()
# rows will either be a queryset, or a list of elements
# matching the type of rows of the table
...
table = Table(
auto__model=Album,
columns__select__include=True,
bulk__actions__submit=Action.submit(post_handler=my_handler)
)
```