### Install django-wildewidgets
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Install the django-wildewidgets package using pip.
```bash
pip install django-wildewidgets
```
--------------------------------
### Local Development Environment Setup
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Steps to clone the repository, navigate to the demo directory, and synchronize dependencies using uv.
```bash
git clone git@github.com:caltechads/django-wildewidgets.git
cd django-wildewidgets/demo
uv sync
```
--------------------------------
### Run Service and Initialize Database
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Starts the service in detached mode and then executes a command within the running container to initialize the database.
```bash
make dev-detached
make exec
> ./manage.py migrate
```
--------------------------------
### Basic Model Table Configuration
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Example of configuring a BasicModelTable with required and optional settings.
```python
class BasicTable(BasicModelTable):
model = MyModel
fields = ['field1', 'related__field2', 'field3']
hidden = ['field3']
unsortable = ['field1']
unsearchable = ['related__field2']
verbose_names = {
'field1': 'First Field',
'related__field2': 'Related Field'
}
actions = [
('View', 'my-view-url', 'get', 'info', 'id'),
('Edit', 'my-edit-url', 'post', 'warning')
]
form_actions = [
('delete', 'Delete Selected')
]
form_url = 'my-form-action-url'
page_length = 25
small = True
buttons = True
striped = True
hide_controls = True
field_types = {
'field1': 'currency'
}
alignment = {
'field2': 'right'
}
bool_icons = {
'field3': [('check-lg', 'success'), ('x-lg', 'danger')]
}
```
--------------------------------
### Install django-markdownify dependency
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/install.rst
Install django-markdownify if you plan to use the Markdown Widget.
```bash
pip install django-markdownify
```
--------------------------------
### Install Altair for Charts
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Install Altair if you plan to use Altair charts with django-wildewidgets.
```bash
pip install altair
```
--------------------------------
### Kibana Log Search Queries
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Example Kibana queries to filter logs for the cheetah-demo application in test and prod environments, excluding health check messages.
```bash
application:"cheetah-demo" AND environment:test AND NOT message:HealthChecker
```
```bash
application:"cheetah-demo" AND environment:prod AND NOT message:HealthChecker
```
--------------------------------
### Embed Altair Chart (Asynchronous)
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/altairchart.html
Use this snippet to embed an Altair chart when the chart data needs to be fetched asynchronously. It makes a GET request to the wildewidgets_json endpoint to retrieve the chart specification before rendering.
```html
{% if options.title %}
### {{ options.title }}
{% endif %}
$(document).ready(function() {
$.get('{% url "wildewidgets_json" %}?wildewidgetclass={{wildewidgetclass}}', function(data) { var spec = data['data'];
var opt = {"renderer": "canvas", "actions": false};
vegaEmbed("#{{name}}", spec, opt);
});
});
```
--------------------------------
### Build Docker Image
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Builds the Docker image for the Cheetah Demo application using the make command.
```bash
make build
```
--------------------------------
### Configure INSTALLED_APPS for Markdown Widget
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/install.rst
If using the Markdown Widget, ensure 'markdownify' is also in your INSTALLED_APPS.
```python
INSTALLED_APPS = [
...
'markdownify',
]
```
--------------------------------
### Copying Docker Environment File
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Copies the Docker environment file to the system's context directory. Ensure you have the necessary permissions.
```bash
cp etc/environment.txt /etc/context.d/demo.env
```
--------------------------------
### Add 'wildewidgets' to INSTALLED_APPS
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Configure your Django project's settings.py to include 'wildewidgets' in INSTALLED_APPS.
```python
INSTALLED_APPS = [
...
'wildewidgets',
]
```
--------------------------------
### Basic Menu Items Configuration
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Define menu items for a basic menu by specifying a list of tuples. Each tuple contains the menu item text and its corresponding URL name. Optional arguments for URL parameters can be included.
```python
class MainMenu(BasicMenu):
items = [
('Users', 'core:home'),
('Uploads','core:uploads'),
]
```
--------------------------------
### Submenu Configuration with LightMenu
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Configure submenus by specifying both the main menu class and item, along with the submenu class and item. This allows for hierarchical menu structures.
```python
class TestView(MenuMixin, TemplateView):
menu_class = MainMenu
menu_item = 'Users'
submenu_class = SubMenu
submenu_item = 'Main User Task'
...
```
--------------------------------
### Include CodeWidget Highlighting CSS
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Include the CSS for syntax highlighting if using the CodeWidget.
```html
```
--------------------------------
### View Mixin for Menu Selection
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Use MenuMixin in a view class to associate a specific menu and highlight a menu item. This simplifies menu management across multiple views.
```python
class TestView(MenuMixin, TemplateView):
menu_class = MainMenu
menu_item = 'Users'
...
```
--------------------------------
### Configure Markdownify settings
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/install.rst
Optionally configure markdownify settings in your settings.py for the Markdown Widget.
```python
MARKDOWNIFY = {
"default": {
"WHITELIST_TAGS": bleach.sanitizer.ALLOWED_TAGS + ["p", "h1", "h2"]
},
}
```
--------------------------------
### Include Wildewidgets URLconf
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Add the WildewidgetDispatch URL configuration to your project's urls.py.
```python
from wildewidgets import WildewidgetDispatch
urlpatterns = [
...
path('/wildewidgets_json', WildewidgetDispatch.as_view(), name='wildewidgets_json'),
]
```
--------------------------------
### Stacked Bar Chart Initialization with Chart.js
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/stackedbarchart.html
Initializes a Chart.js stacked bar chart using data provided by Django template variables. Includes options for responsiveness, titles, legends, and custom tooltip formatting for monetary values.
```html
$(document).ready(function() { var ctx = document.getElementById('{{name}}').getContext('2d'); var myChart = new Chart(ctx, { type: "{{options.chart_type}}", data: { labels:{{labels|safe}}, datasets:{{datasets|safe}} }, options: { responsive: false, {% if options.title %} title: { display: true, text: '{{options.title}}' }, {% endif %} legend: { display: {% if options.legend %}true{% else %}false{% endif %}, position: '{{options.legend_position}}' }, {% if options.money %} tooltips: { callbacks: { label: function(tooltipItem, data) { var label = '' if (data.datasets[tooltipItem.datasetIndex].label) { label = data.datasets[tooltipItem.datasetIndex].label + ": " } var value; {% if options.chart_type == 'horizontalBar' %} value = Math.round(tooltipItem.xLabel * 100) / 100 {% else %} value = Math.round(tooltipItem.yLabel * 100) / 100 {% endif %} value = value.toLocaleString() return label + '$' + value; } } }, {% endif %} {% if options.yAxes_name %} scales: { {{options.yAxes_name}}:[{ stacked: {{options.stacked}}, ticks: { beginAtZero: true, {% if options.money or options.thousands %} callback: function(value, index, values) { var adj = value; {% if options.thousands %} value = value/1000 + 'K'; {% endif %} {% if options.money %} value = '$' + value; {% endif %} return value; } {% endif %} } }], {{options.xAxes_name}}:[{ stacked: {{options.stacked}}, // use these for histogram //categoryPercentage: 1.0, //barPercentage: .98, }], } {% endif %} } }); });
```
--------------------------------
### Include ApexCharts
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Include the ApexCharts JavaScript library for interactive charts.
```html
```
--------------------------------
### Initialize Chart.js with Wildewidgets Data
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/categorychart.html
This snippet initializes a Chart.js chart using data provided by the Django Wildewidgets backend. It handles both synchronous and asynchronous data loading and applies various customization options.
```html
{% if typeof abbreviateNumber == 'undefined' %} {% var SI_SYMBOL = ["", "K", "M", "G", "T", "P", "E"] %} {% assign abbreviateNumber = function(number) { var tier = Math.floor(Math.log10(number) / 3); if(tier == 0) return number; var suffix = SI_SYMBOL[tier]; var scale = Math.pow(10, tier * 3); var scaled = number / scale; return scaled.toFixed(1) + suffix; } %} {% endif %} $(document).ready(function() { {% if async %} $.get('{% url "wildewidgets_json" %}?wildewidgetclass={{wildewidgetclass}}{% if extra_data %}&extra_data={{extra_data}}{% endif %}', function(data) { {% endif %} var ctx = document.getElementById('{{name}}').getContext('2d'); {% if options.chartjs_font_family %} Chart.defaults.global.defaultFontFamily = "{{options.chartjs_font_family|safe}}"; {% endif %} var myChart = new Chart(ctx, { type: "{{options.chart_type}}", {% if async %} data: data, {% else %} data: { labels:{{labels|safe}}, datasets:{{datasets|safe}} }, {% endif %} options: { responsive: false, {% if options.title %} title: { display: true, text: '{{options.title}}', {% if options.chartjs_title_font_size %} fontSize: {{options.chartjs_title_font_size}}, {% endif %} {% if options.chartjs_title_font_style %} fontStyle: '{{options.chartjs_title_font_style}}', {% endif %} {% if options.chartjs_title_padding %} padding: {{options.chartjs_title_padding}}, {% endif %} }, {% endif %} legend: { display: {% if options.legend %}true{% else %}false{% endif %}, position: '{{options.legend_position}}' }, {% if options.money %} tooltips: { callbacks: { label: function(tooltipItem, data) { var label = '' if (data.datasets[tooltipItem.datasetIndex].label) { label = data.datasets[tooltipItem.datasetIndex].label + ": " } var value; {% if options.yAxes_name == 'xAxes' %} value = Math.round(tooltipItem.xLabel * 100) / 100 {% else %} value = Math.round(tooltipItem.yLabel * 100) / 100 {% endif %} value = value.toLocaleString() return label + '$' + value; } } }, {% endif %} {% if options.yAxes_name %} scales: { {{options.yAxes_name}}:[{ stacked: {% if options.stacked %}true{% else %}false{% endif %}, ticks: { beginAtZero: true, {% if options.money or options.thousands %} callback: function(value, index, values) { {% if options.thousands %} value = abbreviateNumber(value); {% comment %} if (value > 1000) { value = value/1000 + 'K'; }{% endcomment %} {% endif %} {% if options.money %} value = '$' + value; {% endif %} return value; } {% endif %} } }], {{options.xAxes_name}}:[{ display: {% if options.histogram %}false{% else %}true{% endif %}, stacked: {% if options.stacked %}true{% else %}false{% endif %}, {% if options.max %} ticks: { max: {{options.max}}, }, {% endif %} // use these for histogram {% if options.histogram %} categoryPercentage: 1.0, barPercentage: 1.0, {% endif %} }, {% if options.histogram %} { display: true, {% if options.histogram_max %} ticks: { //autoSkip: false, max: {{options.histogram_max}}, }, {% endif %} gridLinesx : { display : false } } {% endif %} ], } {% endif %} } }); {% if options.url %} $('#{{name}}').click(function(event){ var firstPoint = myChart.getElementAtEvent(event)[0] if (firstPoint) { var label = myChart.data.labels[firstPoint._index] var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index] var urlprefix = "{{options.url}}"; if (urlprefix.includes("?")) { window.location.href = urlprefix + "&label=" + label + "&value=" + value; } else { window.location.href = urlprefix + "?label=" + label + "&value=" + value; } } }); {% endif %} {% if async %} }); {% endif %} });
```
--------------------------------
### Include DataTables Resources
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Include JavaScript and CSS for DataTables, including moment.js for datetime sorting.
```html
```
--------------------------------
### Define Altair Chart with AJAX using Custom Wildewidgets Class
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/scientific_charts.rst
Create a custom AltairChart subclass in a 'wildewidgets.py' file to define charts that can be loaded via AJAX. Override the 'load' method to set up the Altair spec.
```python
import pandas as pd
import altair as alt
from wildewidgets import AltairChart
class SciChart(AltairChart):
def load(self):
data = pd.DataFrame({
'a': list('CCCDDDEEE'),
'b': [2, 7, 4, 1, 2, 6, 8, 4, 10]
}
)
spec = alt.Chart(data).mark_point().encode(
x='a',
y='b'
)
self.set_data(spec)
```
--------------------------------
### Import DataTable
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Import the DataTable class from the wildewidgets library.
```python
from wildewidgets import DataTable
```
--------------------------------
### DataTables Initialization with Options
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/table.html
Initializes a DataTables instance with various configuration options for DOM manipulation, buttons, language, searching, paging, and column definitions. This is typically used for setting up interactive tables.
```javascript
var {{name}} = $('.{{name}}').DataTable({
dom: '<"d-flex justify-content-between px-3 my-3"<"d-flex flex-row"l{{options.buttons|yesno:"B,'',''}}">f>rtip',
{% if options.buttons %} buttons: [
{ extend: 'copy', className: 'btn btn-info btn-sm ms-1', exportOptions: {columns:export_column_checker}},
{ extend: 'csv', className: 'btn btn-info btn-sm ms-1', exportOptions: {columns:export_column_checker}},
{ extend: 'pdf', className: 'btn btn-info btn-sm ms-1', exportOptions: {columns:export_column_checker}},
{ extend: 'print', className: 'btn btn-info btn-sm ms-1', exportOptions: {columns:export_column_checker}},
], {% endif %}
language: dt_language,
searching: {{options.searchable|yesno:"true,false,true"}},
paging: {{options.paging|yesno:"true,false,true"}},
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
{% if options.page_length %}pageLength: {{options.page_length}},{% endif %}
fnDrawCallback: function(oSettings) {
if (oSettings.aoData.length < this.api().page.len() && this.api().page.info().pages == 1) {
$("#" + oSettings.sTableId + "_paginate").hide();
$("#" + oSettings.sTableId + "_info").hide();
// $("#" + oSettings.sTableId + "_length").hide();
} else {
$("#" + oSettings.sTableId + "_paginate").show();
$("#" + oSettings.sTableId + "_info").show();
// $("#" + oSettings.sTableId + "_length").show();
}
},
order: [[{{form.is_visible|yesno:'1,0,0'}}, "{{sort_ascending|yesno:'asc,desc,asc'}}"]],
columns: [
{% for key,item in header.items %}
{
{% if async %}data: '{{item.field}}',{% endif %}
orderable: {{item.sortable|yesno:"true,false"}},
searchable: {{item.searchable|yesno:"true,false"}},
visible: {{item.visible|yesno:"true,false"}},
className: "dt-body-{{item.align}} dt-head-{{item.head_align}} {{item.wrap|yesno:",dt-body-nowrap,"}}",
},
{% endfor %}
],
createdRow: function(row,data,index,cells) {
{% for item in stylers %}
var testVal = Array.isArray(data) ? data[{{item.test_index}}] : data.{{item.test_cell}};
if (testVal=="{{item.cell_value}}") {
{% if item.is_row %} $(row).addClass("{{item.css_class}}"); {% else %} cells[{{item.target_index}}].classList.add('{{item.css_class}}'); {% endif %}
}
{% endfor %}
},
{% if async %} processing: true,
serverSide: true,
ajax: '{% url ajax_url_name %}?wildewidgetclass={{tableclass}}{% if extra_data %}&extra_data={{extra_data}}{% endif %}&csrf_token={{csrf_token}}'
{% endif %}
});
```
--------------------------------
### TemplateWidget Basic Implementation
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Implement a TemplateWidget by defining the template name and optionally overriding get_context_data to provide data for the template.
```python
class HelloWorldWidget(TemplateWidget):
template_name = 'core/hello_world.html'
def get_context_data(self, **kwargs):
kwargs['data'] = "Hello world"
return kwargs
```
--------------------------------
### Doughnut Chart Initialization
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/doughnutchart_json.html
Initializes a doughnut chart using Chart.js. It fetches data from a URL and configures chart options based on template variables. Use this for dynamic chart generation on a webpage.
```html
```
--------------------------------
### Stacked Bar Chart Rendering with Chart.js
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/stackedbarchart_json.html
This JavaScript code fetches chart data and initializes a Chart.js stacked bar chart. It includes options for responsiveness, titles, legends, and custom tooltips for monetary values or thousands.
```html
$(document).ready(function() { $.get('{% url "wildewidgets_json" %}?wildewidgetclass={{wildewidgetclass}}', function(data) { var ctx = document.getElementById('{{name}}').getContext('2d'); var myChart = new Chart(ctx, { type: "{{options.chart_type}}", data: data, options: { responsive: false, {% if options.title %} title: { display: true, text: '{{options.title}}' }, {% endif %} legend: { display: {% if options.legend %}true{% else %}false{% endif %}, position: '{{options.legend_position}}' }, {% if options.money %} tooltips: { callbacks: { label: function(tooltipItem, data) { var label = '' if (data.datasets[tooltipItem.datasetIndex].label) { label = data.datasets[tooltipItem.datasetIndex].label + ": " } var value = Math.round(tooltipItem.yLabel * 100) / 100 value = value.toLocaleString() return label + '$' + value; } } }, {% endif %} {% if options.yAxes_name %} scales: { {{options.yAxes_name}}:[{ stacked: {{options.stacked}}, ticks: { beginAtZero: true, {% if options.money or options.thousands %} callback: function(value, index, values) { var adj = value; {% if options.thousands %} value = value/1000 + 'K'; {% endif %} {% if options.money %} value = '$' + value; {% endif %} return value; } {% endif %} } }], {{options.xAxes_name}}:[{ stacked: {{options.stacked}}, // use these for histogram //categoryPercentage: 1.0, //barPercentage: .98, }] } {% endif %} } }); }); });
```
--------------------------------
### Include Altair Resources
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Include the necessary JavaScript libraries for Altair scientific charts.
```html
```
--------------------------------
### Terraform Workspace Management
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/README.md
Commands to manage Terraform workspaces for different environments (test, prod). Ensure you are in the 'terraform' directory before executing.
```bash
cd terraform
chtf __LATEST_VERSION__
terraform init --upgrade
terraform workspace select test
```
```bash
terraform workspace select prod
```
```bash
terraform workspace list
```
--------------------------------
### Custom Rendering for Incomplete Trips
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Renders a warning icon for incomplete trips. An empty string is returned if the trip is completed.
```python
def render_open_trip_column(self, row, column):
if not row.completed:
return ''
else:
return ''
```
--------------------------------
### Include ChartJS for Charts
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Include the ChartJS JavaScript library for regular business charts.
```html
```
--------------------------------
### Render Widget List in Django Template
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/widget-list--main.html
This snippet shows a basic Django template structure for iterating through a list of 'entries' (widgets) and rendering each one using the 'wildewidgets' template tags. Ensure 'wildewidgets' is loaded at the top of your template.
```html
{% extends 'wildewidgets/block.html' %}
{% load wildewidgets %}
{% block block_content %}
{% for widget in entries %}
{% wildewidgets widget.get_title %}
{% wildewidgets widget %}
{% endfor %}
{% endblock %}
```
--------------------------------
### Include WidgetListLayout CSS
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/install.rst
Add the necessary CSS file for WidgetListLayout to your template.
```django
{% static 'wildewidgets/css/wildewidgets.css' %}
```
--------------------------------
### Menu Item Iteration and Rendering
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/menu.html
Iterates through menu items, rendering regular items with links and current item indicators. Handles submenus by iterating through their items.
```django
{% for item,data in menu.items %} {% if data.kind == 'item' %}* [{% if vertical %}{{item|truncatechars:28}}{% else %}{{item}}{% endif %} {% if item == active %}(current){% endif %}]({{data.url}}{{data.extra}})
{% elif data.kind == 'submenu' %}* [{{item}}](#)
{% for subitem in data.items %} {% if subitem.divider %}
{% else %} [{% if vertical %}{{subitem.title|truncatechars:21}}{% else %}{{subitem.title}}{% endif %}]({{subitem.url}}{{subitem.extra}}) {% endif %} {% endfor %}
{% else %}* [{{data.kind}}](#)
{% endif %} {% endfor %}
```
--------------------------------
### Import Business Chart Types
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Import the necessary chart classes from the wildewidgets library for use in your Django views.
```python
from wildewidgets import (
BarChart,
DoughnutChart,
HorizontalStackedBarChart,
HorizontalBarChart,
PieChart,
StackedBarChart,
)
```
--------------------------------
### Implement Select All Checkbox Functionality
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/table.html
Handles the 'select all' checkbox, synchronizing its state (checked, indeterminate) with the selection status of individual checkboxes in the table body. Requires 'has_form_actions' and 'options.has_select_all' to be true.
```javascript
{% if has_form_actions and options.has_select_all %} $('#{{ name }}-select-all').on('change', function() {
$('.{{ name }} tbody input[name=checkbox]').prop('checked', this.checked);
});
$('.{{ name }}').on('change', 'tbody input[name=checkbox]', function() {
var total = $('.{{ name }} tbody input[name=checkbox]').length;
var checked = $('.{{ name }} tbody input[name=checkbox]').filter(':checked').length;
$('#{{ name }}-select-all').prop( 'checked', total > 0 && checked === total ).prop( 'indeterminate', checked > 0 && checked < total );
});
{% endif %}
```
--------------------------------
### Include Wildewidgets CSS
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
Add the main Wildewidgets CSS file to your template's head section.
```html
```
--------------------------------
### Reusable Menu Mixin Subclass
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Create a subclass of MenuMixin to reuse menu configuration across several views. This reduces redundancy in view definitions.
```python
class UsersMenuMixin(MenuMixin):
menu_class = MainMenu
menu_item = 'Users'
```
```python
class TestView(UsersMenuMixin, TemplateView):
...
```
--------------------------------
### TabbedWidget with Multiple Tabs
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/widgets.rst
Create a TabbedWidget by adding multiple tabs, each containing a WidgetStream with its own set of widgets. This organizes content into distinct, selectable tabs.
```python
class TestTabbedWidget(TabbedWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
widgets = WidgetStream()
widgets.add_widget(Test1Header())
widgets.add_widget(Test1Table())
self.add_tab("Test 1", widgets)
widgets = WidgetStream()
widgets.add_widget(Test2Header())
widgets.add_widget(Test2Table())
self.add_tab("Test 2", widgets)
```
--------------------------------
### Defining a Basic Model Table
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Define a table by subclassing BasicModelTable and specifying the model, fields, hidden fields, verbose names, actions, form actions, and form URL.
```python
from wildewidgets import BasicModelTable
class TestTable(BasicModelTable):
model = SpecialGroup
fields = ['group', 'account__description', 'group_type', 'name', 'description', 'network_id']
hidden = ['name', 'network_id']
verbose_names = {'account__description':'Account'}
actions = [('Nag', 'core:nag', 'post')]
form_actions = [('action1', 'Action 1'), ('action2', 'Action 2')]
form_url = reverse_lazy('core:action_test')
```
--------------------------------
### Bar Chart Rendering with Chart.js
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/barchart.html
This JavaScript code fetches data from a JSON URL and renders a bar chart using Chart.js. It dynamically configures chart options based on template variables.
```javascript
$(document).ready(function() { $.get('{% url json_url %}', function(data) { var ctx = document.getElementById('{{name}}').getContext('2d'); var myChart = new Chart(ctx, { type: "bar", data: data, {% comment %} datax: { labels: {{labels|safe}}, datasets: [ {% for dataset in datasets %} { data:{{dataset.data|safe}}, {% if dataset.label %} label: '{{dataset.label}}', {% endif %} {% if dataset.backgroundcolor %} backgroundColor: '{{dataset.backgroundcolor}}', {% endif %} {% if dataset.bordercolor %} borderColor: '{{dataset.bordercolor}}', {% endif %} {% if dataset.borderwidth %} borderWidth: '{{dataset.borderwidth}}', {% endif %} }, {% endfor %} ] }, {% endcomment %} options: { {% if options.title %} title: { display: true, text: '{{options.title}}' }, {% endif %} {% if not options.legend %} legend: { display: false }, {% endif %} {% if options.money %} tooltips: { callbacks: { label: function(tooltipItem, data) { var label = '' if (data.datasets[tooltipItem.datasetIndex].label) { label = data.datasets[tooltipItem.datasetIndex].label + ": " } var value = Math.round(tooltipItem.yLabel * 100) / 100 value = value.toLocaleString() return label + '$' + value; } } }, {% endif %} scales: { yAxes: [{ {% if options.stacked %} stacked: true, {% endif %} ticks: { beginAtZero: true, {% if options.money or options.thousands %} callback: function(value, index, values) { var adj = value; {% if options.thousands %} value = value/1000 + 'K'; {% endif %} {% if options.money %} value = '$' + value; {% endif %} return value; } {% endif %} } }], xAxes: [{ {% if options.stacked %} stacked: true, {% endif %} }], } } }); }); });
```
--------------------------------
### Define a Histogram Chart Without AJAX
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Implement a Histogram chart that builds its data directly during initialization. Use for smaller datasets where immediate data loading is acceptable.
```python
class TestHistogram(Histogram): # without ajax
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
mu = 0
sigma = 50
nums = []
bin_count = 40
for i in range(10000):
temp = random.gauss(mu,sigma)
nums.append(temp)
self.build(nums, bin_count)
```
--------------------------------
### Define a Non-AJAX Bar Chart in a Django View
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Instantiate and configure a HorizontalStackedBarChart with data and display it in a Django template. Best for smaller datasets.
```python
class HomeView(TemplateView):
template_name = "core/home.html"
def get_context_data(self, **kwargs):
barchart = HorizontalStackedBarChart(title="New Customers Through July", money=True, legend=True, width='500', color=False)
barchart.set_categories(["January", "February", "March", "April", "May", "June", "July"])
barchart.add_dataset([75, 44, 92, 11, 44, 95, 35], "Central")
barchart.add_dataset([41, 92, 18, 35, 73, 87, 92], "Eastside")
barchart.add_dataset([87, 21, 94, 13, 90, 13, 65], "Westside")
kwargs['barchart'] = barchart
return super().get_context_data(**kwargs)
```
--------------------------------
### Tab Block Template Structure
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/page_tab_block.html
This is the main template for rendering a tab block. It extends a base block template, loads wildewidgets tags, iterates through tabs to display their names, and renders a wildewidgets widget.
```html
{% extends 'wildewidgets/block.html' %}
{% load wildewidgets %}
{% block block_content %}
{% for tab in tabs %}{{tab.name}}
{% endfor %}
{% wildewidgets widget %}
{% endblock %}
```
--------------------------------
### Wildewidgets Block Rendering Logic
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/block.html
This snippet demonstrates the core template logic for rendering a block with wildewidgets. It handles dynamic attributes, CSS IDs and classes, data-bs attributes, ARIA attributes, and iterates through block content, rendering wildewidgets or safe HTML.
```html
{% load wildewidgets %}
<{{tag}}{% for key, value in attributes.items %} {{key}}="{{value}}"{% endfor %}{% if css_id is not None %} id="{{css_id}}"{% endif %}{% if css_classes is not None %} class="{{css_classes}}"{% endif %}{% for key, value in data_attributes.items %} data-bs-{{key}}="{{value}}"{% endfor %}{% for key, value in aria_attributes.items %} aria-{{key}}="{{value}}"{% endfor %}>
{% block block_content %}
{% for content in blocks %}
{% if content|is_wildewidget %}
{% wildewidgets content %}
{% else %}
{{content|safe}}
{% endif %}
{% endfor %}
{% endblock %}
{% if script %}
{{script|safe}}
{% endif %}
```
--------------------------------
### CSS for Dividers and Custom Height
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/demo/users/templates/registration/login.html
Provides CSS rules for creating dividers and setting custom heights for elements, including responsive adjustments for smaller screens.
```css
.divider:after, .divider:before {
content: "";
flex: 1;
height: 1px;
background: #eee;
}
.h-custom {
height: calc(100% - 73px);
}
@media (max-width: 450px) {
.h-custom {
height: 100%;
}
}
```
--------------------------------
### Render ApexChart in Django Template
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/apex_chart.html
This snippet shows how to initialize and render an ApexChart within a Django template. It assumes chart options are passed safely from the Django backend.
```html
$(document).ready(function() { var options_{{css_id}} = {{options|safe}}; var chart_{{css_id}} = new ApexCharts(document.querySelector("#chart_{{css_id}}"), options_{{css_id}}); chart_{{css_id}}.render(); {% block js_extra %} {% endblock %} });
```
--------------------------------
### Conditional Brand Display in Menu
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/menu.html
Renders a brand image with a link if available, otherwise renders brand text with a link. Falls back to nothing if neither is present.
```django
{% if brand_image %} [ ]({{brand_url}}){% elif brand_text %} [{{brand_text}}]({{brand_url}}) {% else %}
{% endif %}
```
--------------------------------
### Embed Altair Chart (Synchronous)
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/altairchart.html
Use this snippet to embed an Altair chart when the chart data is directly available in the template context. It initializes vegaEmbed with the chart specification and rendering options.
```html
{% if options.title %}
### {{ options.title }}
{% endif %}
$(document).ready(function() {
var spec = {{data|safe}};
var opt = {"renderer": "canvas", "actions": false};
vegaEmbed("#{{name}}", spec, opt);
});
```
--------------------------------
### Django Template Tags for Static and Internationalization
Source: https://github.com/caltechads/django-wildewidgets/blob/main/demo/demo/users/templates/registration/login.html
Loads necessary Django template tags for managing static files and internationalization. This is a standard practice in Django projects.
```html
{% load static i18n sass_tags %}
```
--------------------------------
### Define DataTable with Ajax Source
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Create a custom DataTable class inheriting from DataTable, specifying a model and columns for AJAX-sourced data.
```python
from wildewidgets import DataTable
class TestTable(DataTable):
model = Measurement
def __init__(self, *args, **kwargs):
if not "table_id" in kwargs:
kwargs["table_id"] = "data_measurement"
super().__init__(*args, **kwargs)
self.add_column('name')
self.add_column('time', searchable=False)
self.add_column('pressure')
self.add_column('temperature')
self.add_column('restricted', visible=False)
self.add_column('open', sortable=False)
```
--------------------------------
### Define a Custom Stacked Bar Chart for AJAX Loading
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Create a custom chart class inheriting from StackedBarChart to load data asynchronously. Override methods to provide categories, dataset labels, and datasets.
```python
from wildewidgets import StackedBarChart
class TestChart(StackedBarChart):
def get_categories(self):
"""Return 7 labels for the x-axis."""
return ["January", "February", "March", "April", "May", "June", "July"]
def get_dataset_labels(self):
"""Return names of datasets."""
return ["Central", "Eastside", "Westside", "Central2", "Eastside2", "Westside2", "Central3", "Eastside3", "Westside3"]
def get_datasets(self):
"""Return 3 datasets to plot."""
return [[750, 440, 920, 1100, 440, 950, 350],
[410, 1920, 180, 300, 730, 870, 920],
[870, 210, 940, 3000, 900, 130, 650],
[750, 440, 920, 1100, 440, 950, 350],
[410, 920, 180, 2000, 730, 870, 920],
[870, 210, 940, 300, 900, 130, 650],
[750, 440, 920, 1100, 440, 950, 3500],
[410, 920, 180, 3000, 730, 870, 920],
[870, 210, 940, 300, 900, 130, 650]]
```
--------------------------------
### Display Chart in Django Template (AJAX)
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/scientific_charts.rst
Render the chart object (defined using the custom class) in the Django template. The Wildewidgets library handles the AJAX loading mechanism.
```django
{{scichart}}
```
--------------------------------
### Include DataTables export buttons
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/install.rst
Add JavaScript files for DataTables export buttons (HTML5, print) and required dependencies like jszip and pdfmake.
```html
```
--------------------------------
### Use Custom AJAX Chart in Django View
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Instantiate the custom AJAX chart class in your Django view and pass it to the template context. Suitable for large datasets.
```python
from .wildewidgets import TestChart
class HomeView(TemplateView):
template_name = "core/home.html"
def get_context_data(self, **kwargs):
kwargs['barchart'] = TestChart(width='500', height='400', thousands=True)
return super().get_context_data(**kwargs)
```
--------------------------------
### Wildewidgets Template Structure
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/widget-list.html
This snippet shows a typical Django template extending a base Wildewidgets template and using various Wildewidgets tags to define content areas. It includes a loop for rendering multiple modal widgets.
```html
{% extends 'wildewidgets/block.html' %}
{% load wildewidgets %}
{% block block_content %}
{% wildewidgets header %}
{% wildewidgets sidebar %}
{% wildewidgets main %}
{% for modal in modals %}
{% wildewidgets modal %}
{% endfor %}
{% endblock %}
```
--------------------------------
### Initialize Default Column Filters
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/table.html
Iterates through defined filters and applies default values to table columns if specified. This is useful for pre-filtering data on page load.
```django
{% for batch in filters %} {% with field_counter=forloop.counter0 filter=batch.1 item=batch.0 %} {% if filter and filter.default %} // var {{name}}.column('{{field_counter}}').search('{{filter.default_value}}').draw(); {% endif %} {% endwith %} {% endfor %}
```
--------------------------------
### Loading and Displaying Wildewidgets Table in Template
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Load the wildewidgets templatetag in your Django template and use the 'wildewidgets' tag to display the table, ensuring the CSRF token is included.
```django_template
{% load wildewidgets %}
{% wildewidgets table %}
```
--------------------------------
### Define Altair Chart in Django View (No AJAX)
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/scientific_charts.rst
Import necessary libraries and define an Altair chart within a Django view's context data. This method is suitable for direct rendering without AJAX.
```python
import pandas as pd
import altair as alt
from wildewidgets import AltairChart
class AltairView(TemplateView):
template_name = "core/altair.html"
def get_context_data(self, **kwargs):
data = pd.DataFrame({
'a': list('CCCDDDEEE'),
'b': [2, 7, 4, 1, 2, 6, 8, 4, 7]
}
)
spec = alt.Chart(data).mark_point().encode(
x='a',
y='b'
)
chart = AltairChart(title='Scientific Proof')
chart.set_data(spec)
kwargs['chart'] = chart
return super().get_context_data(**kwargs)
```
--------------------------------
### Implementing Conditional Action Buttons
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Override the get_conditional_action_buttons method to return an action button only when a specific condition is met for a given row.
```python
def get_conditional_action_buttons(self, row):
if condition:
return self.get_action_button(row, 'Action', 'core:myaction')
return ''
```
--------------------------------
### Include Tabler CSS
Source: https://github.com/caltechads/django-wildewidgets/blob/main/README.md
If using Tabler UI, include the additional CSS file for table enhancements.
```html
```
--------------------------------
### Define a Histogram Chart With AJAX
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/business_charts.rst
Create a Histogram chart that loads its data asynchronously. The build function is called within the load method for AJAX-enabled data fetching.
```python
class TestHorizontalHistogram(HorizontalHistogram): # with ajax
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_color(False)
def load(self):
mu = 100
sigma = 30
nums = []
bin_count = 50
for i in range(10000):
temp = random.gauss(mu,sigma)
nums.append(temp)
self.build(nums, bin_count)
```
--------------------------------
### Custom Date Column Rendering
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Overrides the default date column rendering to format the date as 'Month Day, Year'.
```python
def render_date_column(self, row, column):
return row.date.strftime("%B %-d, %Y")
```
--------------------------------
### Wildewidgets Simple Block Template
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/block--simple.html
This Django template snippet renders a block element with dynamic attributes, including standard HTML attributes, CSS classes, data attributes, and ARIA attributes. It also supports embedding custom scripts.
```html
<{{tag}}{% for key, value in attributes.items %} {{key}}="{{value}}"{% endfor %}{% if css_id is not None %} id="{{css_id}}"{% endif %}{% if css_classes is not None %} class="{{css_classes}}"{% endif %}{% for key, value in data_attributes.items %} data-bs-{{key}}="{{value}}"{% endfor %}{% for key, value in aria_attributes.items %} aria-{{key}}="{{value}}"{% endfor %}> {% if script %} {{script|safe}} {% endif %}
```
--------------------------------
### Crispy Form Modal Template
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/crispy_form_modal.html
Extends a base modal template and renders a crispy form. Ensure 'crispy_forms_tags' is loaded.
```html
{% extends 'wildewidgets/modal.html' %}
{% load crispy_forms_tags %}
{% block modal_body %}
{% crispy form %}
{% endblock %}
```
--------------------------------
### Use Custom Altair Chart Class in Django View (AJAX)
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/scientific_charts.rst
Instantiate the custom SciChart class within a Django view's context data. This allows the chart to be loaded dynamically, typically via AJAX.
```python
from .wildewidgets import SciChart
class HomeView(TemplateView):
template_name = "core/altair.html"
def get_context_data(self, **kwargs):
kwargs['scichart'] = SciChart()
return super().get_context_data(**kwargs)
```
--------------------------------
### Use Custom DataTable in View
Source: https://github.com/caltechads/django-wildewidgets/blob/main/docs/tables.rst
Instantiate the custom DataTable class in a Django view for AJAX-sourced data.
```python
from .wildewidgets import TestTable
class TableView(TemplateView):
template_name = "core/tables.html"
def get_context_data(self, **kwargs):
kwargs['table'] = TestTable()
return super().get_context_data(**kwargs)
```
--------------------------------
### Fetch and Update ApexChart Data
Source: https://github.com/caltechads/django-wildewidgets/blob/main/wildewidgets/templates/wildewidgets/apex_json.html
This JavaScript code fetches JSON data from a specified URL and updates the series of an ApexChart. Ensure the chart object (e.g., `chart_{{css_id}}`) is initialized before this script runs.
```html
{% extends "wildewidgets/apex_chart.html" %} {% block js_extra %} var url = '{% url "wildewidgets_json" %}?wildewidgetclass={{wildewidgetclass}}{% if extra_data %}&extra_data={{extra_data}}{% endif %}&csrf_token={{csrf_token}}'; $.getJSON(url, function(data) { chart_{{css_id}}.updateSeries(data['series']); }); {% endblock %}
```