### Install django-jsonform Source: https://github.com/bhch/django-jsonform/blob/master/README.md Install the library using pip. This command fetches and installs the latest version of django-jsonform. ```sh pip install django-jsonform ``` -------------------------------- ### Results List: With Thumbnails Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Example of a results list including file paths and thumbnail paths. ```python [ {'value': 'path/to/file.jpg', 'thumbnail': 'path/to/thumb.jpg',}, ... ] ``` -------------------------------- ### Results List: With Metadata and File Info Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Example of a results list with file paths, thumbnails, and detailed metadata. ```python [ { 'value': 'path/to/file.jpg', 'thumbnail': 'path/to/thubnail.jpg', 'metadata': { 'name': 'Name of image', 'date': '01 Jan, 2022', 'size': '100 KB', } }, ... ] ``` -------------------------------- ### Implement File List GET View Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Handle GET requests in your file handler view to return a list of available files. Implement pagination to manage large numbers of files. ```python from django.http import JsonResponse from django.contrib.auth.decorators import login_required @login_required def file_handler(request): if request.method == 'POST': # save uploaded file ... elif request.method == 'GET': page = int(request.GET.get('page', 1)) files_per_page = 10 start = (page - 1) * files_per_page end = start + files_per_page results = [] for obj in MediaModel.objects.all()[start:end]: results.append({ 'value': obj.file.name, ``` -------------------------------- ### Results List: File Names Only Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Example of a results list containing only file paths. ```python [ {'value': 'path/to/file.jpg'}, # file 1 {'value': 'path/to/file.jpg'}, # file 2 ... ] ``` -------------------------------- ### Autocomplete Handler View Example Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/autocomplete.rst This is an example of a Django view that handles AJAX requests for the autocomplete widget. It requires user login and returns a JSON response with search results. ```python from django.http import JsonResponse from django.contrib.auth.decorators import login_required @login_required def autocomplete_handler(request): query = request.GET.get('query') # search query # ... do something ... results = [ 'Australia', 'Brazil', ] return JsonResponse({'results': results}) ``` -------------------------------- ### String Input Types Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/inputs.rst Examples of different string input types. Use 'format' for specific string types like date or email, and 'widget' for UI elements like textarea. ```python # 1. Text input (default) { 'type': 'string' } ``` ```python # 2. Date input { 'type': 'string', 'format': 'date' } ``` ```python # 3. Email input { 'type': 'string', 'format': 'email' } ``` ```python # 4. Textarea input { 'type': 'string', 'widget': 'textarea' } ``` -------------------------------- ### Registering File Handler URL in Django Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Example of how to add a URL pattern for the file handler view in your Django app's urls.py. ```python # myapp/urls.py from django.urls import path urlpatterns = [ # ... path('json-file-handler/', myapp.views.file_handler_view), # ... ] ``` -------------------------------- ### Object Schema Example Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Defines a schema for a dictionary with specific keys, their types, and default values. Use this for structured data input where fields are predefined. ```python # Schema { 'type': 'dict', # or 'object' 'keys': { # or 'properties' 'name': { 'type': 'string' }, 'email': { 'type': 'string' }, 'age': { 'type': 'number', 'title': 'Age in years', 'default': 50, # default value for age 'readonly': True, # make it readonly } }, 'required': ['email'] } # Output data { 'name': 'John Doe', 'email': 'john@example.com', 'age': 99 } ``` -------------------------------- ### Basic File Handler View Outline Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst A basic Django view outline for handling file uploads (POST), listing files (GET), and deleting files (DELETE). Requires login. ```python # Basic file handler view from django.contrib.auth.decorators import login_required @login_required def file_handler_view(request): if request.method == 'POST': # save uploaded file ... elif request.method == 'GET': # return available files for choosing ... elif request.method == 'DELETE': # delete files ... ``` -------------------------------- ### Array Schema Example Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Defines a schema for a list of strings with constraints on the number of items and default values. Use this for creating forms that manage ordered collections of data. ```python # Schema { 'type': 'list', # or 'array' 'items': { 'type': 'string', 'default': 'Hello', # default value for new items 'readonly': True, # make all items readonly }, 'minItems': 1, 'maxItems': 5, 'default': ['One', 'Two', 'Three'], # initial value for the whole list } # Output data ['one', 'two', 'three', ...] ``` -------------------------------- ### Demo Schema for Dynamic Choices Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst This is the schema used in the practical example for dynamically updating choices in a form. The 'vehicle' choices are initially empty and populated based on the 'category' selection. ```python { 'type': 'object', 'title': 'Mode of transportation', 'keys': { 'category': { 'type': 'string', 'choices': ['Land', 'Water', 'Air'] }, 'vehicle': { 'type': 'string', 'choices': [] # vehicle choices will be added dynamically } } } ``` -------------------------------- ### Referencing Schema with $ref Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst The '$ref' keyword allows reusing schema definitions, promoting DRY principles and enabling recursive structures. This example shows how 'shipping_address' reuses the schema defined for 'billing_address'. ```json { 'type': 'object', 'properties': { 'billing_address': { 'type': 'object', 'properties': { 'street': { 'type': 'string' }, 'city': { 'type': 'string' }, 'state': { 'type': 'string' } } }, 'shipping_address': { '$ref': '#/properties/billing_address' } } } ``` -------------------------------- ### Const Keyword Example Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Use the 'const' keyword to define a field with a fixed, unchangeable value. It defaults to a readonly input and can be hidden with the 'hidden' widget. ```python # Schema { 'type': 'object', 'title': 'Human', 'properties': { 'species': { 'const': 'Homo sapiens' }, 'name': { 'type': 'string' }, }, } ``` -------------------------------- ### Get Current Form Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Retrieve the current schema of the form instance using the getSchema() method. ```javascript formInstance.getSchema() ``` -------------------------------- ### Get Current Form Data Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Retrieve the current data of the form instance using the getData() method. ```javascript formInstance.getData() ``` -------------------------------- ### Get Form Instance using ID Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Use this function to obtain a reference to the form widget instance. The ID is typically formatted as 'id__jsonform'. ```javascript var form = reactJsonForm.getFormInstance('id_my_field_jsonform'); ``` -------------------------------- ### Lazy Translation Example Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/translations.rst Demonstrates how to use Django's gettext_lazy for translating field titles and choice options within a JSONForm schema. This ensures translations are loaded only when needed. ```python from django.utils.translation import gettext_lazy as _ { 'type': 'string', 'title': _('Occupation'), 'choices': [ {'value': 'teacher', 'title': _('Teacher')}, {'value': 'doctor', 'title': _('Doctor')}, {'value': 'engineer', 'title': _('Engineer')}, 'default': 'teacher' } ``` -------------------------------- ### Readonly Inputs Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/inputs.rst Examples of making inputs uneditable using the 'readonly' keyword. This applies to individual string inputs and all items within an array. ```python # 1. String inputs { 'type': 'string', 'readonly': True } ``` ```python # 2. Array items { 'type': 'array', 'items': { 'type': 'string', 'readonly': True # all items will be readonly } } ``` -------------------------------- ### Custom Form with JSONField Validators Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Example of setting custom validators for a JSONField within a Django ModelForm. This is useful for advanced validation scenarios. ```python # models.py class ShoppingList(models.Model): items = JSONField(schema=...) ... # admin.py class ShoppingListForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # set your validators on the form field self.fields['items'].validators = [items_validator] class ShoppingListAdmin(admin.ModelAdmin): form = ShoppingListForm ``` -------------------------------- ### Default Values for Inputs Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/inputs.rst Demonstrates how to set default initial values for various input types using the 'default' keyword. ```python # 1. String input { 'type': 'string', 'default': 'Hello world' } ``` ```python # 2. Boolean { 'type': 'boolean', 'default': True } ``` ```python # 3. Default choice { 'type': 'string', 'choices': ['Eggs', 'Juice', 'Milk'], 'default': 'Milk' } ``` ```python # 4. Default array items { 'type': 'array', 'items': { 'type': 'string', 'default': 'Hello world' # default value for every new array item } } ``` -------------------------------- ### Specify Simple String Choices Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/choices.rst Use the 'choices' keyword with a list of strings for simple selection options. ```python { 'type': 'string', 'choices': ['Eggs', 'Milk', 'Juice'] # you can also use 'enum' keyword } ``` -------------------------------- ### Accessing File URLs in Django Templates Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Demonstrates how to display file URLs in Django templates. It shows how to prepend the media URL prefix using the {% get_media_prefix %} tag. ```django {% load static %} ``` -------------------------------- ### Simple Menu Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/examples.rst Schema for a simple menu structure. Use this to validate menu data. ```python # Schema { 'type': 'list', 'items': { 'type': 'dict', 'keys': { 'label': { 'type': 'string' }, 'link': { 'type': 'string' }, 'new_tab': { 'type': 'boolean', 'title': 'Open in new tab' } } } } ``` -------------------------------- ### Menu Data Structure Source: https://github.com/bhch/django-jsonform/blob/master/docs/examples.rst This is the expected data structure for a simple menu. ```javascript // Data (javascript/json) [ {'label': 'Home', 'link': '/', 'new_tab': false}, {'label': 'About', 'link': '/about/', 'new_tab': false}, {'label': 'Twitter', 'link': 'https://twitter.com/', 'new_tab': true}, ] ``` -------------------------------- ### Autocomplete Widget Schema Configuration Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/autocomplete.rst Configure the autocomplete widget in your schema. Use 'handler' to specify the URL for AJAX requests, which can be a hard-coded URL or a reversed URL using reverse_lazy. ```python # Schema { 'type': 'string', 'widget': 'autocomplete', 'handler': '/url/to/handler_view' # hard-coded url # OR 'handler': reverse_lazy('handler-view-name') # reversed URL } ``` -------------------------------- ### Global File Handler Setting Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Configure a common file handler URL for all JSONFields by setting DJANGO_JSONFORM['FILE_HANDLER'] in settings.py. ```python # settings.py DJANGO_JSONFORM = { 'FILE_HANDLER': '/json-file-handler/' } ``` -------------------------------- ### Autocomplete Response Format with Title and Value Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/autocomplete.rst Options can also be provided as dictionaries with 'title' for display and 'value' for the actual data. This allows for more descriptive options in the autocomplete input. ```python JsonResponse({ 'results': [ {'title': 'Australia', 'value': 'AU'}, {'title': 'Brazil', 'value': 'BR'}, ... ] }) ``` -------------------------------- ### Specify Choices with Custom Titles and Values Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/choices.rst Provide a list of dictionaries to map user-facing titles to underlying values. ```python { 'type': 'string', 'choices': [ {'title': 'New York', 'value': 'NY'}, {'title': 'California', 'value': 'CA'}, {'title': 'Texas', 'value': 'TX'}, ] } ``` -------------------------------- ### Access Nested Data Using Index and Key Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst Demonstrates direct Python access to a nested field ('age') within the sample data structure using list indexing and dictionary key lookup. ```python data[0]['age'] # data > first item > age ``` -------------------------------- ### Add django-jsonform to settings.py Source: https://github.com/bhch/django-jsonform/blob/master/README.md Add 'django_jsonform' to your INSTALLED_APPS in your Django project's settings.py file to enable the app. ```python INSTALLED_APPS = [ # ... 'django_jsonform' ] ``` -------------------------------- ### Implement File Upload POST View Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Create a view function to handle POST requests for file uploads. This view should process the uploaded file, save it to a model, and return the file's path in a JsonResponse. ```python from django.http import JsonResponse from django.contrib.auth.decorators import login_required @login_required def file_handler(request): if request.method == 'POST': file = request.FILES['file'] obj = MediaModel(file=file) obj.save() # return the path of the file # this value will be kept in the JSON data return JsonResponse({'value': obj.file.name}) elif request.method == 'GET': # return available files for choosing ... elif request.method == 'DELETE': # delete files ... ``` -------------------------------- ### Configure DJANGO_JSONFORM Wrapper Setting Source: https://github.com/bhch/django-jsonform/blob/master/docs/settings.rst This is the main dictionary setting to hold all django-jsonform specific configurations. It's essential for defining global behaviors like file handling. ```python DJANGO_JSONFORM = { 'FILE_HANDLER': '' } ``` -------------------------------- ### Configure File Handler within Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Alternatively, define a 'handler' keyword within the schema for a specific field to override global settings. This allows for distinct handlers per field. ```python 'image': { 'type': 'string', 'format': 'file-url', 'handler': '/json-file-handler/' # hard-coded URL # OR 'handler': reverse_lazy('json-file-handler') # reversed URL } ``` -------------------------------- ### Autocomplete Response Format Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/autocomplete.rst The handler view must return a JsonResponse containing a dictionary with a 'results' key. The value should be a list of options. ```python JsonResponse({'results': ['Australia', 'Brazil', ...]}) ``` -------------------------------- ### Enable Multiple Selections with Multiselect Widget Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/choices.rst Use an 'array' type with 'items' configured for 'multiselect' to allow multiple selections. The 'multiselect' widget ensures each value is selected only once. ```python { 'type': 'array', 'items': { 'type': 'string', 'choices': ['Eggs', 'Milk', 'Juice'], 'widget': 'multiselect' } } ``` -------------------------------- ### Nested Menu Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/examples.rst Schema for a menu with nested items, using $ref for recursive structures. Ensure to consult referencing schema documentation for details. ```python # Schema { 'type': 'list', 'items': { 'type': 'dict', 'keys': { 'label': { 'type': 'string' }, 'link': { 'type': 'string' }, 'new_tab': { 'type': 'boolean', 'title': 'Open in new tab' }, 'children': { '$ref': '#' } } } } ``` -------------------------------- ### Define Dynamic Choices with a Callable Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/choices.rst Specify choices dynamically by providing a callable function that returns the schema. This is useful for fetching choices from a database. ```python def dynamic_schema(): # here, you can create a schema dynamically # such as read data from database and populate choices schema = {...} return schema class MyModel(models.Model): items = JSONField(schema=dynamic_schema) ``` -------------------------------- ### Implement Recursive Nesting with $ref Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst The $ref keyword enables recursive schema definitions, allowing objects to contain nested structures of the same type, such as hierarchical menus. Be cautious of infinite loops. ```python { 'type': 'array', 'title': 'Menu', 'items': { 'type': 'object', 'properties': { 'text': { 'type': 'string', 'title': 'Display text for the item' }, 'link': { 'type': 'string', 'title': 'URL of the item' }, 'children': { '$ref': '#' } } } } ``` -------------------------------- ### Use Radio Widget for Choices Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/choices.rst Render choices as radio buttons using the 'widget': 'radio' option. ```python { 'type': 'string', 'choices': ['Eggs', 'Milk', 'Juice'], 'widget': 'radio' } ``` -------------------------------- ### formInstance.getData() Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Retrieves the current data of the form instance. ```APIDOC ## formInstance.getData() ### Description Returns the current data of the form instance. ### Returns - **object** - The current data of the form. ``` -------------------------------- ### formInstance.getSchema() Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Retrieves the current schema of the form instance. ```APIDOC ## formInstance.getSchema() ### Description Returns the current schema of the form instance. ### Returns - **object** - The current schema of the form. ``` -------------------------------- ### Define Sample Data Structure Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst This Python code defines a sample nested data structure representing a list of persons with their ages and children. ```python data = [ { 'name': 'Alice', 'age': 30, 'children':[ { 'name': 'Carl', 'age': 8 } ] }, { 'name': 'Bob', 'age': '40', 'children': [] } ] ``` -------------------------------- ### Enable In-Browser Validation (Form __init__) Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Set `validate_on_submit = True` on the widget within the form's `__init__` method to enable client-side validation before form submission. This provides immediate feedback to the user. ```python # Option 1: In form's __init__ method class ShoppingListForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['items'].widget.validate_on_submit = True ``` -------------------------------- ### Define Reusable Schema with $defs Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Use the $defs keyword to define common schema parts that can be referenced multiple times using $ref. This promotes modularity and reduces redundancy in complex schemas. ```python { 'type': 'object', 'properties': { 'billing_address': { '$ref': '#/$defs/address' }, 'shipping_address': { '$ref': '#/$defs/address' } }, '$defs': { 'address': { 'type': 'object', 'properties': { 'street': { 'type': 'string' }, 'city': { 'type': 'string' }, 'state': { 'type': 'string' } } } } } ``` -------------------------------- ### Load Custom JS Files in Django Admin Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst This Python code demonstrates the quickest way to load custom JavaScript files, like 'my-script.js', into the Django admin interface using the Media class within an admin class. ```python # models.py class MyAdmin(admin.ModelAdmin): ... class Media: js = ('path/to/my-script.js',) ``` -------------------------------- ### formInstance.addEventListener(event, callback) Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Attaches a callback function to a specific event on the form instance. The callback is executed whenever the specified event occurs, providing access to form data and schema. ```APIDOC ## formInstance.addEventListener(event, callback) ### Description Use this function to add a callback function for an event. It will be called every time the event occurs. The callback will receive an object containing these keys: - data: The data of the widget - schema: The schema of the widget - prevData: Previous data (before the event) - prevSchema: Previous schema (before the event) ### Parameters #### Path Parameters - **event** (string) - Required - The name of the event to listen for (e.g., 'change'). - **callback** (function) - Required - The function to execute when the event occurs. ### Request Example ```javascript function onChangeHandler(e) { // do something ... } var form = reactJsonForm.getFormInstance('id_my_field_jsonform'); form.addEventListener('change', onChangeHandler); ``` ``` -------------------------------- ### Combining Schemas with allOf Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Use allOf to specify that all of the subschemas must match the data. This keyword is only supported within an 'object' type and can be used with additionalProperties. ```python { 'type': 'object', 'allOf': [ { 'properties': { 'age': {'type': 'number'} } }, { 'properties': { 'date_of_birth': {'type': 'string', 'format': 'date-time'} } } ], 'additionalProperties': True # additionalProperties can be used with allOf } ``` -------------------------------- ### Create and manage error mappings with ErrorMap Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Use ErrorMap to easily create error mappings for widgets. It's a subclass of dict that simplifies setting and appending error messages for specific field coordinates. ```python from django_jsonform.utils import ErrorMap error_map = ErrorMap() # set an error message error_map.set(coords=[0], msg='This value is invalid') # append error messages on same field error_map.append(coords=[0], msg='Second error message') print(error_map) ``` -------------------------------- ### Add Event Listener to Form Instance Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Attach a callback function to listen for specific events on the form instance. The callback receives an event object with data, schema, and previous states. ```javascript function onChangeHandler(e) { // do something ... } ``` ```javascript var form = reactJsonForm.getFormInstance('id_my_field_jsonform'); form.addEventListener('change', onChangeHandler); ``` -------------------------------- ### Convert ISO Datetime String to Datetime Object in Python Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/inputs.rst Import the 'datetime' class and use 'fromisoformat' to convert an ISO formatted string into a Python datetime object for further processing. ```python from datetime import datetime date_string = '2022-02-06T15:42:11.092+00:00' # ISO string date = datetime.fromisoformat(date_string) # ... do something with the object ... ``` -------------------------------- ### Overriding File Input Widget Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Configure a 'file-url' field to use a simple file input instead of the default modal uploader by setting the 'widget' to 'fileinput'. ```json 'logo': { 'type': 'string', 'format': 'file-url', 'widget': 'fileinput' # will create a simple file input } ``` -------------------------------- ### Map Errors Using Coordinate Strings Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst Illustrates how coordinate strings are used as keys in an error map to associate specific error messages with nested fields. ```python error_map = { '0§age': 'Invalid value', } ``` -------------------------------- ### Schema for File URL Upload Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Use 'string' type with 'file-url' format to store file paths in JSON. This is ideal for larger files and allows server-side management. ```python # Schema { 'type': 'object', 'keys': { 'logo': {'type': 'string', 'format': 'file-url'} } } # Output data { 'logo': 'path/to/logo.png' } ``` -------------------------------- ### Object Schema with Additional Properties Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Allows users to add extra keys to an object beyond those explicitly defined in the schema. Use this when the exact set of keys is not known in advance or can be extended. ```python # Schema { 'type': 'dict', # or 'object' 'keys': { # or 'properties' 'name': { 'type': 'string' }, }, 'addtionalProperties': True # or 'additionalProperties': { 'type': 'string' } } # Output data { 'name': 'John Doe', # declared in the schema 'gender': 'Male', # added by the user } ``` -------------------------------- ### formInstance.update(config) Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Updates the schema or data of a form widget. The config object can contain 'schema' and/or 'data' properties. It's important to call this conditionally within change event listeners to prevent infinite loops. ```APIDOC ## formInstance.update(config) ### Description Updates the schema or data of a form widget. The config object can contain 'schema' and/or 'data' properties. ### Parameters #### Request Body - **config** (object) - Required - An object containing `schema` and/or `data` properties to update the form. - **schema** (object) - Optional - The new schema definition for the form. - **data** (object) - Optional - The new data for the form. ### Request Example ```javascript var config = { schema: { ... }, data: { ... } }; form.update(config); ``` ### Important Note If calling `update` from a `change` event listener, ensure it's conditional (e.g., check if `data` differs from `prevData`) to avoid infinite loops. ``` -------------------------------- ### ErrorMap Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Manages error mappings for widgets, allowing setting and appending error messages to specific field coordinates. ```APIDOC ## ErrorMap ### Description Manages error mappings for widgets. It's a subclass of `dict` that simplifies creating error mappings. ### Methods #### `set(coords, msg)` Sets the given message for the specified coordinates. - **coords** (list) - A list of coordinates of the field. - **msg** (string or list) - A string or a list of error messages. #### `append(coords, msg)` Appends the given message to previously added coordinates. If the coordinates do not exist, it acts like the `set()` method. - **coords** (list) - A list of coordinates of the field. - **msg** (string or list) - A string or a list of error messages. ### Usage Example ```python from django_jsonform.utils import ErrorMap error_map = ErrorMap() # set an error message error_map.set(coords=[0], msg='This value is invalid') # append error messages on same field error_map.append(coords=[0], msg='Second error message') print(error_map) # Expected output: {'0': ['This value is invalid', 'Second error message']} ``` ``` -------------------------------- ### Enable In-Browser Validation (Meta Class) Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Configure `validate_on_submit = True` for the widget directly in the form's `Meta` class. This is an alternative method for enabling client-side validation. ```python # Option 2: In form's Meta class class ShoppingListForm(forms.ModelForm): class Meta: widgets: { 'items': JSONFormWidget(schema=..., validate_on_submit=True) } ``` -------------------------------- ### join_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Generates a string by joining the given coordinates using a specific separator. ```APIDOC ## join_coords(*coords) ### Description Generates a string by joining the given coordinates. Internally uses the section sign (\§) as a separator. ### Parameters - **\*coords** (variable arguments) - A sequence of coordinates to join. ### Usage Example ```python from django_jsonform.utils import join_coords join_coords('person', 0, 'name') # -> 'person§0§name' ``` ``` -------------------------------- ### Conditional Schema Matching with anyOf Source: https://github.com/bhch/django-jsonform/blob/master/docs/schema.rst Use anyOf to specify that at least one of the subschemas must match the data. Cannot be used with additionalProperties. ```python { 'type': 'array', 'items': { 'anyOf': [ {'type': 'number'}, {'type': 'string'} ] } } ``` -------------------------------- ### Split Coordinates String with split_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst Demonstrates the use of the `split_coords` helper function from `django_jsonform.utils` to parse a coordinate string into a list of individual coordinate components. ```python from django_jsonform.utils import split_coords split_coords('0§age') # -> ['0', 'age'] ``` -------------------------------- ### Initialize JSONForm and Set Change Listener Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst This JavaScript code initializes the JSON form instance on page load and attaches a change event listener. It ensures the code runs only when the django-jsonform widget is present. ```javascript // my-script.js window.addEventListener('load', function() { /* We want to run this code after all other scripts have been loaded */ if (window.reactJsonForm) { /* We put this inside a condition because * we only want it to run on those pages where * django-jsonform widget is loaded */ var form = reactJsonForm.getFormInstance('id_my_field_jsonform'); form.addEventListener('change', onJsonFormChange); } }); var vehicleChoiceMap = { 'Land': ['Car', 'Bus', 'Train'], 'Water': ['Ship', 'Boat', 'Submarine'], 'Air': ['Aeroplane', 'Rocket'], }; function onJsonFormChange(e) { var data = e.data; // current data var prevData = e.prevData; // previous data (before this event) var schema = e.schema; // current schema var prevSchema = e.prevSchema; // previous schema (before this event) var selectedCategory = data.category; if (!selectedCategory) { /* no category selected yet, exit the function */ return; } if (selectedCategory === prevData.category) { /* category hasn't changed, no need to update choices */ return; } schema.keys.vehicle.choices = vehicleChoiceMap[selectedCategory]; schema.keys.vehicle.helpText = "Select " + selectedCategory + " vehicle"; data.vehicle = ''; // reset previously selected vehicle form.update({ schema: schema, data: data }) } ``` -------------------------------- ### File Upload Response Format Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Your file handler view must return a JsonResponse with a 'value' key containing the path to the uploaded file. This path will be stored in the JSON data. ```python JsonResponse({'value': 'path/to/uploaded-file.jpg'}) ``` -------------------------------- ### Schema for Base64 File Upload Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Use 'string' type with 'data-url' format for Base64 encoded file data within JSON. This is suitable for small files. ```python # Schema { 'type': 'object', 'keys': { 'logo': {'type': 'string', 'format': 'data-url'} } } # Output data { 'logo': 'data:image/png;base64,' } ``` -------------------------------- ### Access Deeply Nested Data Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst Shows how to access a deeply nested field ('age' of a child) by chaining multiple index and key lookups in Python. ```python data[0]['children'][0]['age'] # data > first item > children > first item > age ``` -------------------------------- ### Image Slider Data Structure Source: https://github.com/bhch/django-jsonform/blob/master/docs/examples.rst This is the expected data structure for an image slider component. ```javascript // Data (javascript/json) [ { 'image': 'images/slide-1.png', 'heading': 'This is slide 1', 'caption': 'This is a caption', 'button': { 'label': 'Sign up', 'link': '/sign-up/' } }, { 'image': 'images/slide-2.png', 'heading': 'This is slide 2', 'caption': 'This is another caption', 'button': { 'label': 'Learn more', 'link': '/learn-more/' } } ] ``` -------------------------------- ### Django File Handler for DELETE Requests Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Implement a Django view to handle DELETE requests for file deletion. This snippet shows how to extract trigger and file names, and return appropriate HTTP status codes. ```python # views.py from django.http import HttpResponse from django.contrib.auth.decorators import login_required @login_required def file_handler(request): if request.method == 'POST': # save uploaded file ... elif request.method == 'GET': # return list of existing files ... elif request.method == 'DELETE': trigger = request.GET.get('trigger') file_names = request.GET.getlist('value') if trigger != 'delete_button': # if deletion is not triggered by Delete button, # exit the view return HttpResponse(status=200) for name in file_names: # ... delete files ... ... return HttpResponse(status=200) # success # OR return HttpResponse(status=403) # permission denied ``` -------------------------------- ### Custom Validator Function with ErrorMap Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Demonstrates how to write a custom validator function for JSONForm. Instead of raising ValidationError, it uses JSONSchemaValidationError and ErrorMap to provide specific error messages for individual fields within the JSON structure. ```python from django_jsonform.exceptions import JSONSchemaValidationError from django_jsonform.utils import ErrorMap def items_validator(value): error_map = ErrorMap() if value[0] != 'Banana': error_map.set(coords=[0], msg='First item in shopping list must be Banana') if value[1] != 'Eggs': error_map.set(coords=[1], msg='Second item in shopping list must be Eggs') ``` -------------------------------- ### Image Slider Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/examples.rst Schema for an image slider, including nested button objects. The 'image' field is formatted as a file URL. ```python # Schema { 'type': 'list', 'items': { 'type': 'dict', 'keys': { 'image': { 'type': 'string', 'format': 'file-url' }, 'heading': { 'type': 'string' }, 'caption': { 'type': 'string' }, 'button': { 'type': 'object', 'keys': { 'label': { 'type': 'string' }, 'link': { 'type': 'string' } } } } } } ``` -------------------------------- ### JsonResponse Response Format Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst This is the standard JSON response format for file uploads, containing a list of results. ```python JsonResponse({ 'results': [ {'value': 'path/to/file-1.jpg'}, # file 1 {'value': 'path/to/file-2.jpg'}, # file 2 ... ]) ``` -------------------------------- ### Generate Coordinates String with join_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/coordinates.rst Utilizes the `join_coords` helper function from `django_jsonform.utils` to create a coordinate string by joining indices and keys. ```python from django_jsonform.utils import join_coords join_coords(0, 'age') # -> '0§age' ``` -------------------------------- ### JSON Schema for Array with Object Items Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst This schema defines an array where each item must be an object with specific properties like 'name' (string, required, max length 30) and 'age' (integer, minimum 18). ```python # Schema { 'type': 'array', 'minItems': 1, 'items': { 'type': 'object', 'properties': { 'name': { 'type': 'string', 'required': True, 'maxLength': 30 }, 'age': { 'type': 'integer', 'minimum': '18' } } } } ``` -------------------------------- ### Join coordinates into a string with join_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Generates a string by joining the given coordinates using the section sign (\u00a7) as a separator. This function is useful for creating unique identifiers for nested form fields. ```python from django_jsonform.utils import join_coords join_coords('person', 0, 'name') # -> 'person§0§name' ``` -------------------------------- ### Usage of JSONSchemaValidator Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Instantiate `JSONSchemaValidator` with a schema and then call its `validate` method with the data to be checked. Invalid data will raise a `JSONSchemaValidationError`. ```python from django_jsonform.validators import JSONSchemaValidator # create a validator instance validator = JSONSchemaValidator(schema=...) # validate the data validate(data) # if the data is invalid, JSONSchemaValidationError will be raised ``` -------------------------------- ### Datetime Field Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/inputs.rst Define a string field with 'datetime' format in your JSON schema to enable the datetime input widget. ```python { 'type': 'string', 'format': 'datetime' # or 'date-time' } ``` -------------------------------- ### Setting Multiple Errors for One Input Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Use `ErrorMap.set()` or `ErrorMap.append()` to provide multiple error messages for a single input field. This is useful when an input violates several validation rules. ```python # using ErrorMap.set() error_map.set(coords=[0], msg=['First error', 'Second error', ...]) # or useing ErrorMap.append() error_map.append(coords=[0], msg=['First error', 'Second error', ...]) ``` -------------------------------- ### Pre-save Hook for JSONField Transformation Source: https://github.com/bhch/django-jsonform/blob/master/docs/fields-and-widgets.rst Implement a pre_save_hook callable for JSONField to transform JSON data before it is saved to the database. The hook receives the current value and must return the value to be saved. ```python def pre_save_hook(value): # do something with the value ... return value class MyModel(...): items = JSONField(schema=..., pre_save_hook=pre_save_hook) ``` -------------------------------- ### Define ArrayField with Base Field and Size Source: https://github.com/bhch/django-jsonform/blob/master/docs/fields-and-widgets.rst Use ArrayField to define a model field that stores an array of a specific base type with an optional size limit. It renders a dynamic form widget. ```python from django_jsonform.models.fields import ArrayField class MyModel(models.Model): items = ArrayField(models.CharField(max_length=50), size=10) # ... ``` -------------------------------- ### reactJsonForm.getFormInstance(id) Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Retrieves an instance of the form widget using its container ID. This instance can then be used to interact with the form programmatically. ```APIDOC ## reactJsonForm.getFormInstance(id) ### Description Use this function to get an instance of the form widget. ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the widget container (e.g., 'id__jsonform'). ### Request Example ```javascript var form = reactJsonForm.getFormInstance('id_my_field_jsonform'); ``` ``` -------------------------------- ### JSONField Specific File Handler Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Specify a handler view for a particular JSONField using the 'file_handler' argument, overriding global settings. ```python # Example usage within a Django model field definition (not shown in source, but implied) # JSONField(..., file_handler='/my-custom-handler/') ``` -------------------------------- ### Load Django JSONForm Template Tags Source: https://github.com/bhch/django-jsonform/blob/master/docs/templatetags.rst Load the django_jsonform template tags at the beginning of your template file before using any of its filters or tags. ```html {% load django_jsonform %} ``` -------------------------------- ### Access Model Instance in Callable Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/fields-and-widgets.rst Manually set the widget's instance attribute in a custom ModelForm to allow callable schemas to access the current model instance. This is necessary because Django initializes widgets before the instance is available. ```python def callable_schema(instance=None): # instance will be None while creating new object if instance: # ... do something with the instance ... else: # ... do something else ... return schema class MyModel(models.Model): my_field = JSONField(schema=callable_schema) ... # admin.py # create a custom modelform class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # manually set the current instance on the widget self.fields['my_field'].widget.instance = self.instance # set the form on the admin class class MyAdmin(admin.ModelAdmin): form = MyModelForm admin.site.register(MyModel, MyAdmin) ``` -------------------------------- ### Split a coordinate string into individual coordinates with split_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Splits a coordinate string into individual coordinates using the section sign (\u00a7) as the delimiter. This is the inverse operation of join_coords. ```python from django_jsonform.utils import split_coords split_coords('person§0§name') # -> ['person', '0', 'name'] ``` -------------------------------- ### Providing Errors for Deeply Nested Inputs Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/validation.rst Specify the exact location of an invalid input using a list of coordinates in `error_map.set()`. This allows precise error reporting for complex, nested structures. ```python from django_jsonform.utils import ErrorMap error_map = ErrorMap() # error message for 'quantity' of '0' (first item) error_map.set(coords=[0, 'quantity'], msg='Minimum quantity must be 5') ``` -------------------------------- ### Register Model with Django Admin Source: https://github.com/bhch/django-jsonform/blob/master/docs/quickstart.rst Register your custom model with the Django admin site to enable CRUD operations through the admin interface. This makes the model accessible for management. ```python from django.contrib import admin from myapp.models import ShoppingList admin.site.register(ShoppingList) ``` -------------------------------- ### Configure JSONFormWidget with Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/fields-and-widgets.rst Use JSONFormWidget in Django admin to specify a schema for a model field. Ensure the schema is accessible, like a class attribute. ```python class ShoppingListForm(forms.ModelForm): class Meta: model = ShoppingList fields = '__all__' widgets = { 'items': JSONFormWidget(schema=ShoppingList.ITEMS_SCHEMA) } class ShoppingListAdmin(admin.ModelAdmin): form = ShoppingListForm admin.site.register(ShoppingList, ShoppingListAdmin) ``` -------------------------------- ### Update Form Schema or Data Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/javascript.rst Use the update function to modify the schema or data of a JSON form widget. The config object should contain schema and/or data properties. ```javascript var config = { schema: ..., data: ..., } form.update(config); ``` -------------------------------- ### Iterating and Rendering Widget Attributes in Django Template Source: https://github.com/bhch/django-jsonform/blob/master/django_jsonform/templates/django_jsonform/attrs.html This snippet demonstrates how to loop through widget attributes in a Django template, conditionally rendering them based on their value. Attributes that are not False and not 'id' or 'required' are processed. If an attribute's value is not True, it's rendered as a string. ```django {% for name, value in widget.attrs.items %}{% if value is not False and name not in 'id,required' %} {{ name }}{% if value is not True %}="{{ value|stringformat:'s' }}"{% endif %}{% endif %}{% endfor %} ``` -------------------------------- ### split_coords Source: https://github.com/bhch/django-jsonform/blob/master/docs/utils.rst Splits a coordinates string into individual coordinates using a specific separator. ```APIDOC ## split_coords(coords) ### Description Splits a coordinates string into individual coordinates. Uses the section sign (\§) as the separator. ### Parameters - **coords** (string) - The coordinates string to split. ### Usage Example ```python from django_jsonform.utils import split_coords split_coords('person§0§name') # -> ['person', '0', 'name'] ``` ``` -------------------------------- ### Configure File Handler in Django Model Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/upload.rst Set the file_handler attribute in your model's JSONField to specify a URL for handling file uploads. You can use a hard-coded URL or a reversed URL for flexibility. ```python from django.urls import reverse_lazy class MyModel(...): data = JSONField( schema=..., file_handler='/json-file-handler/' # hard-coded URL # OR file_handler=reverse_lazy('name-of-url') # reversed URL ) ``` -------------------------------- ### Basic ArrayField Usage in Django Model Source: https://github.com/bhch/django-jsonform/blob/master/docs/guide/arrayfield.rst Define a Django model with an ArrayField from django-jsonform. This field allows for a list of items, with a specified size limit and element type. ```python from django_jsonform.models.fields import ArrayField class MyModel(models.Model): items = ArrayField(models.CharField(max_length=50), size=10) ``` -------------------------------- ### Define JSONFormField with Schema Source: https://github.com/bhch/django-jsonform/blob/master/docs/fields-and-widgets.rst Use JSONFormField to define a form field that handles JSON data with a specified schema. This is useful when not using model fields directly. ```python from django_jsonform.forms.fields import JSONFormField class MyForm(forms.Form): my_field = JSONFormField(schema=schema) ```