askrobots / PyStructUI
Public
Transform data structures into HTML for any Python web framework. Works with Flask, Django, FastAPI. No templates needed - just data. Switch between Bootstrap, Tailwind, Material UI with one line.
django_views.py · 6.9 KB · 229 lines
| 1 | """ |
| 2 | Django + PyStructUI Example |
| 3 | Shows how to use data structures instead of Django templates |
| 4 | |
| 5 | Add to your Django project's views.py: |
| 6 | """ |
| 7 | |
| 8 | from django.http import HttpResponse |
| 9 | from django.shortcuts import redirect |
| 10 | from django.views import View |
| 11 | from pystructui import django_integration |
| 12 | |
| 13 | # Initialize PyStructUI |
| 14 | ui = django_integration(renderer='bootstrap') |
| 15 | |
| 16 | # Simulate a database (in real app, use Django models) |
| 17 | todos = [] |
| 18 | |
| 19 | |
| 20 | def index(request): |
| 21 | """Home page using data structures instead of templates""" |
| 22 | data = { |
| 23 | 'type': 'page', |
| 24 | 'title': 'Django + PyStructUI Demo', |
| 25 | 'components': [ |
| 26 | { |
| 27 | 'type': 'navbar', |
| 28 | 'brand': 'Django Todo', |
| 29 | 'links': [ |
| 30 | {'text': 'Home', 'url': '/'}, |
| 31 | {'text': 'Admin', 'url': '/admin/'}, |
| 32 | {'text': 'API', 'url': '/api/'}, |
| 33 | ] |
| 34 | }, |
| 35 | { |
| 36 | 'type': 'hero', |
| 37 | 'title': 'Django Without Templates!', |
| 38 | 'subtitle': 'Use data structures instead of HTML', |
| 39 | 'variant': 'success' |
| 40 | }, |
| 41 | _render_todo_section() |
| 42 | ] |
| 43 | } |
| 44 | |
| 45 | return ui.render_response(data) |
| 46 | |
| 47 | |
| 48 | def _render_todo_section(): |
| 49 | """Generate todo section as data structure""" |
| 50 | todo_items = [] |
| 51 | |
| 52 | for i, todo in enumerate(todos): |
| 53 | todo_items.append({ |
| 54 | 'type': 'raw', |
| 55 | 'content': f""" |
| 56 | <div class="list-group-item d-flex justify-content-between align-items-center"> |
| 57 | <span>{todo['text']}</span> |
| 58 | <span> |
| 59 | <span class="badge bg-primary rounded-pill me-2">{todo.get('category', 'general')}</span> |
| 60 | <a href="/delete/{i}" class="btn btn-sm btn-danger">Delete</a> |
| 61 | </span> |
| 62 | </div> |
| 63 | """ |
| 64 | }) |
| 65 | |
| 66 | return { |
| 67 | 'type': 'card', |
| 68 | 'title': '📋 Your Todos', |
| 69 | 'body': { |
| 70 | 'type': 'raw', |
| 71 | 'content': f""" |
| 72 | <form method="POST" action="/add" class="mb-3"> |
| 73 | <div class="input-group"> |
| 74 | <input type="text" name="todo_text" class="form-control" placeholder="Add a new todo..." required> |
| 75 | <select name="category" class="form-select" style="max-width: 150px;"> |
| 76 | <option value="personal">Personal</option> |
| 77 | <option value="work">Work</option> |
| 78 | <option value="urgent">Urgent</option> |
| 79 | </select> |
| 80 | <button class="btn btn-primary" type="submit">Add</button> |
| 81 | </div> |
| 82 | </form> |
| 83 | <div class="list-group"> |
| 84 | {''.join([ui.render(item) for item in todo_items]) if todo_items else '<p class="text-muted">No todos yet!</p>'} |
| 85 | </div> |
| 86 | """ |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | |
| 91 | class TodoAPIView(View): |
| 92 | """API endpoint returning data structures as JSON""" |
| 93 | |
| 94 | def get(self, request): |
| 95 | """Return todos as data structure""" |
| 96 | data = { |
| 97 | 'type': 'api_response', |
| 98 | 'status': 'success', |
| 99 | 'data': { |
| 100 | 'todos': todos, |
| 101 | 'count': len(todos) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | # Could return as JSON or HTML |
| 106 | if request.GET.get('format') == 'html': |
| 107 | return ui.render_response(self._wrap_in_page(data)) |
| 108 | |
| 109 | import json |
| 110 | return HttpResponse( |
| 111 | json.dumps(data), |
| 112 | content_type='application/json' |
| 113 | ) |
| 114 | |
| 115 | def _wrap_in_page(self, data): |
| 116 | """Wrap API response in page structure""" |
| 117 | return { |
| 118 | 'type': 'page', |
| 119 | 'title': 'API Response', |
| 120 | 'components': [ |
| 121 | {'type': 'navbar', 'brand': 'Django API'}, |
| 122 | { |
| 123 | 'type': 'card', |
| 124 | 'title': 'API Response', |
| 125 | 'body': { |
| 126 | 'type': 'raw', |
| 127 | 'content': f'<pre class="bg-dark text-white p-3">{import.json.dumps(data, indent=2)}</pre>' |
| 128 | } |
| 129 | } |
| 130 | ] |
| 131 | } |
| 132 | |
| 133 | |
| 134 | def add_todo(request): |
| 135 | """Handle adding a todo""" |
| 136 | if request.method == 'POST': |
| 137 | todo_text = request.POST.get('todo_text') |
| 138 | category = request.POST.get('category', 'general') |
| 139 | if todo_text: |
| 140 | todos.append({ |
| 141 | 'text': todo_text, |
| 142 | 'category': category |
| 143 | }) |
| 144 | |
| 145 | return redirect('/') |
| 146 | |
| 147 | |
| 148 | def delete_todo(request, index): |
| 149 | """Delete a todo by index""" |
| 150 | if 0 <= index < len(todos): |
| 151 | todos.pop(index) |
| 152 | return redirect('/') |
| 153 | |
| 154 | |
| 155 | # Class-based view example |
| 156 | class DashboardView(View): |
| 157 | """Dashboard using class-based views""" |
| 158 | |
| 159 | def get(self, request): |
| 160 | stats = self._calculate_stats() |
| 161 | |
| 162 | data = { |
| 163 | 'type': 'page', |
| 164 | 'title': 'Dashboard', |
| 165 | 'components': [ |
| 166 | { |
| 167 | 'type': 'navbar', |
| 168 | 'brand': 'Dashboard', |
| 169 | }, |
| 170 | { |
| 171 | 'type': 'grid', |
| 172 | 'columns': 4, |
| 173 | 'items': [ |
| 174 | self._stat_card('Total Todos', stats['total'], 'primary'), |
| 175 | self._stat_card('Personal', stats['personal'], 'info'), |
| 176 | self._stat_card('Work', stats['work'], 'success'), |
| 177 | self._stat_card('Urgent', stats['urgent'], 'danger'), |
| 178 | ] |
| 179 | }, |
| 180 | { |
| 181 | 'type': 'table', |
| 182 | 'headers': ['Task', 'Category', 'Actions'], |
| 183 | 'rows': [ |
| 184 | [todo['text'], todo.get('category', 'general'), f'<a href="/delete/{i}">Delete</a>'] |
| 185 | for i, todo in enumerate(todos) |
| 186 | ] |
| 187 | } |
| 188 | ] |
| 189 | } |
| 190 | |
| 191 | return ui.render_response(data) |
| 192 | |
| 193 | def _calculate_stats(self): |
| 194 | """Calculate todo statistics""" |
| 195 | stats = { |
| 196 | 'total': len(todos), |
| 197 | 'personal': len([t for t in todos if t.get('category') == 'personal']), |
| 198 | 'work': len([t for t in todos if t.get('category') == 'work']), |
| 199 | 'urgent': len([t for t in todos if t.get('category') == 'urgent']), |
| 200 | } |
| 201 | return stats |
| 202 | |
| 203 | def _stat_card(self, title, value, variant): |
| 204 | """Generate a statistics card""" |
| 205 | return { |
| 206 | 'type': 'card', |
| 207 | 'body': { |
| 208 | 'type': 'raw', |
| 209 | 'content': f""" |
| 210 | <h6 class="text-muted">{title}</h6> |
| 211 | <h2 class="text-{variant}">{value}</h2> |
| 212 | """ |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | |
| 217 | # URLs configuration (add to urls.py) |
| 218 | """ |
| 219 | from django.urls import path |
| 220 | from . import views |
| 221 | |
| 222 | urlpatterns = [ |
| 223 | path('', views.index, name='index'), |
| 224 | path('add', views.add_todo, name='add_todo'), |
| 225 | path('delete/<int:index>', views.delete_todo, name='delete_todo'), |
| 226 | path('api/', views.TodoAPIView.as_view(), name='api'), |
| 227 | path('dashboard/', views.DashboardView.as_view(), name='dashboard'), |
| 228 | ] |
| 229 | """ |