### Migrate StreamField Options with Django Migrations Source: https://github.com/raagin/django-streamfield/blob/master/README.md Provides an example of a Django migration that uses the `migrate_stream_options` function from `streamfield.base` to update existing StreamField data when new options are introduced. This is necessary to ensure default values are applied correctly. ```python # migration from django.db import migrations from streamfield.base import migrate_stream_options def migrate_options(apps, schema_editor): Page = apps.get_model("main", "Page") for page in Page.objects.all(): page.stream = migrate_stream_options(page.stream) page.save() class Migration(migrations.Migration): dependencies = [ '...' # Specify your dependencies here ] operations = [ migrations.RunPython(migrate_options), ] ``` -------------------------------- ### Get StreamField Data as a List Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates how to retrieve StreamField data as a list of dictionaries using the `.as_list()` method. This format is useful for iterating through blocks and rendering them individually in templates. ```Python # views.py stream_list = page.stream.as_list() # You will get list of dictionaries # print(stream_list) [{ 'data': { 'block_model': '.....', 'block_unique_id': '....', 'block_content': [...], 'as_list': True, 'options': {} }, 'template': '....' }, ... ] ``` -------------------------------- ### Define StreamField Models in Django Source: https://github.com/raagin/django-streamfield/blob/master/README.md This snippet shows how to define models for use as blocks within Django StreamField. It includes examples of a single object block (RichText) and a list of objects block (ImageWithText), demonstrating how to set model names and options like `as_list` for list-based blocks. ```Python from django.db import models # one object class RichText(models.Model): text = models.TextField(blank=True, null=True) def __str__(self): # This text will be added to block title name. # For better navigation when block is collapsed. return self.text[:30] class Meta: # This will use as name of block in admin # See also STREAMFIELD_BLOCK_TITLE in settings verbose_name="Text" # list of objects class ImageWithText(models.Model): image = models.ImageField(upload_to="folder/") text = models.TextField(null=True, blank=True) # StreamField option for list of objects as_list = True def __str__(self): # This text will be added to block title name. # For better navigation when block is collapsed. return self.text[:30] class Meta: verbose_name="Image with text" verbose_name_plural="Images with text" ``` -------------------------------- ### Render StreamField with Extra Context using Template Tag Source: https://github.com/raagin/django-streamfield/blob/master/README.md Provides an example of using the `stream_render` template tag from `streamfield_tags` to pass additional context variables, such as 'request' and 'page', to StreamField blocks for use in their templates. ```HTML {% load streamfield_tags %} ...
{% stream_render page.stream request=request page=page %}
... ``` -------------------------------- ### Add StreamField to INSTALLED_APPS Source: https://github.com/raagin/django-streamfield/blob/master/README.md Integrates the 'streamblocks' and 'streamfield' applications into your Django project's settings. ```Python INSTALLED_APPS = [ ... 'streamblocks', 'streamfield', ... ] ``` -------------------------------- ### Enable Admin Help Text in StreamField Settings Source: https://github.com/raagin/django-streamfield/blob/master/README.md Explains how to configure the `STREAMFIELD_SHOW_ADMIN_HELP_TEXT` setting in Django's `settings.py` to display a 'Help' link within the admin interface for StreamField blocks. ```python # settings.py STREAMFIELD_SHOW_ADMIN_HELP_TEXT = True ``` -------------------------------- ### Add Global Options to StreamField Blocks Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to use `STREAMFIELD_BLOCK_OPTIONS` in `settings.py` to define global options that can be applied to all blocks within a StreamField. These options can then be accessed within block templates. ```python STREAMFIELD_BLOCK_OPTIONS = { "margins": { "label": "Margins", "type": "checkbox", "default": True } } # In block template: {{ options.margins }} ``` -------------------------------- ### Include StreamField URLs Source: https://github.com/raagin/django-streamfield/blob/master/README.md Appends the StreamField URLs to your project's main URL configuration. ```Python urlpatterns += [ path('streamfield/', include('streamfield.urls')) ] ``` -------------------------------- ### Include StreamField Blocks in Template Iteration Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows a template snippet for iterating through the list of StreamField blocks obtained via `.as_list()` and rendering each block using its associated template and data. ```HTML {% for b in page.stream.as_list %} {% include b.template with block_content=b.data.block_content %} {% endfor %} ``` -------------------------------- ### Set Custom Help Text for StreamField Admin Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates how to provide custom HTML content for the help text displayed in the StreamField admin interface by setting the `STREAMFIELD_ADMIN_HELP_TEXT` variable in `settings.py`. ```python STREAMFIELD_ADMIN_HELP_TEXT = '

Text

' ``` -------------------------------- ### Django Admin Change Form Template Source: https://github.com/raagin/django-streamfield/blob/master/streamfield/templates/streamfield/admin/change_form.html This snippet shows the base template for a Django admin change form, including loading static files, internationalization, and admin-specific tags. It defines blocks for form content, error display, field sets, and submission buttons. ```Django Template Language {% extends "admin/change_form.html" %}{% load static i18n admin_modify admin_urls %} {% block content %} {% csrf_token %}{% block form_top %}{% endblock %} {% if is_popup %}{% endif %} {% if request.GET.block_id and is_popup %}{% endif %} {% if request.GET.instance_id and is_popup %}{% endif %} {% if request.GET.app_id and is_popup %}{% endif %} {% if errors %} {% if errors|length == 1 %}{% trans "Please correct the error below." %}{% else %}{% trans "Please correct the errors below." %}{% endif %} {% for error in adminform.form.non_field_errors %}* {{ error }} {% endfor %} {% endif %} {% block field_sets %} {% for fieldset in adminform %} {% include "admin/includes/fieldset.html" %} {% endfor %} {% endblock %} {% block after_field_sets %}{% endblock %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_forms %} {% include inline_admin_formset.opts.template %} {% endfor %} {% endblock %} {% block after_related_objects %}{% endblock %} {% block submit_buttons_bottom %}{% submit_row %}{% endblock %} {% prepopulated_fields_js %} {% endblock %} ``` -------------------------------- ### Add Extra Options to StreamField Blocks Source: https://github.com/raagin/django-streamfield/blob/master/README.md Illustrates how to use the 'extra_options' property to add block-specific options that supplement or override options defined in Django settings for StreamField blocks. ```Python class Slide(models.Model): ... extra_options = { "autoplay": { "label": "Autoplay", "type": "checkbox", "default": False } } ... ``` -------------------------------- ### Render StreamField in Template (Template Tag) Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates rendering StreamField content using a template tag, allowing for extra context like the request object. ```HTML {% load streamfield_tags %} ...
{% stream_render page.stream request=request %}
... ``` -------------------------------- ### Custom Admin Template for Blocks Source: https://github.com/raagin/django-streamfield/blob/master/README.md Explains how to provide custom admin templates for block models by placing them in the 'admin' subdirectory within the app's templates. ```HTML streamblocks/templates/streamblocks/admin/richtext.html ``` -------------------------------- ### Custom Admin Class for Blocks Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to create a custom admin class for block models by inheriting from StreamBlocksAdmin and Django's ModelAdmin. ```Python # streamblocks/admin.py from django.contrib import admin from streamfield.admin import StreamBlocksAdmin from streamblocks.models import RichText admin.site.unregister(RichText) @admin.register(RichText) class RichTextBlockAdmin(StreamBlocksAdmin, admin.ModelAdmin): pass ``` -------------------------------- ### Create Abstract Blocks in StreamField Source: https://github.com/raagin/django-streamfield/blob/master/README.md Explains how to create abstract block models in StreamField, which are useful for blocks that only contain templates and do not store data in the database, such as widgets or separators. ```Python class EmptyBlock(models.Model): class Meta: abstract = True verbose_name='Empty space' ``` -------------------------------- ### Register StreamField Models Source: https://github.com/raagin/django-streamfield/blob/master/README.md Defines a list of models to be used with StreamField. Avoids using reserved field names like 'as_list' or 'options'. ```Python STREAMBLOCKS_MODELS = [ RichText, ImageWithText ] ``` -------------------------------- ### Define Block Options for StreamField Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to define additional options for StreamField blocks using the 'options' property in the block's model. These options can be used in templates and appear in the admin interface, supporting types like checkbox, text, and select. ```Python # streamblocks/models.py # list of objects as slider class Slide(models.Model): image = models.ImageField(upload_to="folder/") text = models.TextField(null=True, blank=True) # StreamField option for list of objects as_list = True options = { 'autoplay': { 'label': 'Autoplay slider', 'type': 'checkbox', 'default': False }, 'width': { 'label': 'Slider size', 'type': 'select', 'default': 'wide', 'options': [ {'value': 'wide', 'name': 'Wide slider'}, {'value': 'narrow', 'name': 'Narrow slider'}, ] }, 'class_name': { 'label': 'Class Name', 'type': 'text', 'default': '' } } class Meta: verbose_name="Slide" verbose_name_plural="Slider" ``` -------------------------------- ### Add Blocks Programmatically to StreamField Source: https://github.com/raagin/django-streamfield/blob/master/README.md Illustrates how to add different types of blocks (e.g., RichText, ImageWithText) to a StreamField instance programmatically. It also covers the necessary steps to refresh the model instance from the database before adding blocks if the instance is newly created. ```python r = RichText(text='

Lorem ipsum

') im1 = ImageWithText.objects.create(image='...') im2 = ImageWithText.objects.create(image='...') page.stream.add(r) page.stream.add([im1, im2]) page.save() ``` ```python page = Page() page.save() page.refresh_from_db() ``` -------------------------------- ### Extend Default Admin Render Template Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to extend the default StreamField admin render template to add custom content. ```HTML {% extends "streamfield/admin/change_form_render_template.html" %} {% block streamblock_form %} {{ block.super }} Original object is: {{ object }} {% endblock streamblock_form %} ``` -------------------------------- ### Render StreamField in Template (Cached) Source: https://github.com/raagin/django-streamfield/blob/master/README.md Illustrates rendering the StreamField content directly in a Django template using its cached property. ```HTML ...
{{ page.stream.render }}
... ``` -------------------------------- ### Configure StreamField Block Popup Size Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to set the dimensions for the popup window used when editing blocks within the StreamField. The `popup_size` attribute can be added to the StreamField definition in your Django models. ```python stream = StreamField( model_list=[...], popup_size=(1000, 500) # default value. Width: 1000px, Height: 500px ) ``` -------------------------------- ### Define StreamField in Model Source: https://github.com/raagin/django-streamfield/blob/master/README.md Shows how to add a StreamField to a Django model, specifying the list of allowed block models. ```Python # models.py from streamfield.fields import StreamField from streamblocks.models import RichText, ImageWithText class Page(models.Model): stream = StreamField( model_list=[ RichText, ImageWithText ], verbose_name="Page blocks" ) ``` -------------------------------- ### Copy StreamField Objects in Django Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates how to create a deep copy of StreamField objects, ensuring that all instances within the field are also copied. This is crucial when duplicating an entire Django model instance that contains a StreamField. ```python page.pk = None page.stream = page.stream.copy() page.save() ``` -------------------------------- ### RichText Block Template Source: https://github.com/raagin/django-streamfield/blob/master/README.md Provides an HTML template for rendering the RichText block content, displaying text safely. ```HTML
{{ block_content.text|safe }}
``` -------------------------------- ### ImageWithText Block Template Source: https://github.com/raagin/django-streamfield/blob/master/README.md Defines an HTML template for rendering blocks containing an image and text, iterating through multiple items. ```HTML ``` -------------------------------- ### Override StreamField Blocks in Django Admin Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates how to dynamically override the list of blocks available for a StreamField in the Django admin interface based on specific object conditions. This allows for context-aware block selection. ```Python from streamfield.fields import StreamFieldWidget from streamblocks.models import RichText from .models import Page @admin.register(Page) class PageAdmin(models.Admin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if obj and obj.id == 1: form.base_fields['stream'].widget = StreamFieldWidget(attrs={ 'model_list': [ RichText ] }) return form ``` -------------------------------- ### Specify Custom Admin Template Option Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates setting a custom admin template for a block model using the 'custom_admin_template' attribute. ```Python class RichText(models.Model): ... custom_admin_template = "streamblocks/admin/richtext.html" ... ``` -------------------------------- ### Custom Admin Field Rendering Source: https://github.com/raagin/django-streamfield/blob/master/README.md Explains how to override the rendering of specific block fields in the admin by creating custom templates in the 'admin/fields/' directory. ```HTML streamblocks/templates/streamblocks/admin/fields/textarea.html ``` ```HTML streamblocks/templates/streamblocks/admin/fields/my_custom_widget.html ``` -------------------------------- ### Admin Template Context Variables Source: https://github.com/raagin/django-streamfield/blob/master/README.md Details the context variables available ('form', 'object') when using custom admin templates for block models. ```HTML {{ form.text.value }} {{ object }} ``` -------------------------------- ### Specify Custom Block Template Source: https://github.com/raagin/django-streamfield/blob/master/README.md Demonstrates how to set a custom template for a block model using the 'block_template' attribute. ```Python class RichText(models.Model): ... block_template = "streamblocks/richtext.html" ... ``` -------------------------------- ### Django StreamField Block Title Configuration Source: https://github.com/raagin/django-streamfield/blob/master/changes2.0.md Demonstrates how to define a block title in Django StreamField using the `__str__` method for better navigation. Alternatively, the block title can be customized via Django settings. ```Python from django.db import models from wagtail.core.blocks import StructBlock class MyBlock(StructBlock): # ... block fields ... def __str__(self): return "My Custom Block Title" # Or in settings.py: # STREAMFIELD_BLOCK_TITLE = 'custom_method_name' ``` -------------------------------- ### Cache StreamField Rendered HTML Source: https://github.com/raagin/django-streamfield/blob/master/README.md Presents a method for caching the rendered HTML output of a StreamField to reduce database requests. This involves rendering the stream to a separate field, like 'stream_rendered', within the model's save method. ```Python def save(self, *args, **kwargs): self.stream_rendered = self.stream.render super().save(*args, **kwargs) ... ``` -------------------------------- ### Admin Field Rendering Context Source: https://github.com/raagin/django-streamfield/blob/master/README.md Details the 'field' context variable available when using custom templates for rendering block fields in the admin. ```HTML {{ field.value|default:""|safe }} ``` -------------------------------- ### Control Database Deletion of StreamField Blocks Source: https://github.com/raagin/django-streamfield/blob/master/README.md Details the `STREAMFIELD_DELETE_BLOCKS_FROM_DB` setting, which controls whether block instances are deleted from the database when removed from a StreamField. Setting it to `False` preserves these instances. ```python STREAMFIELD_DELETE_BLOCKS_FROM_DB = False ``` -------------------------------- ### Customize StreamField Block Titles Source: https://github.com/raagin/django-streamfield/blob/master/README.md Explains the `STREAMFIELD_BLOCK_TITLE` setting (version > 2.0.1) for customizing how block names are displayed in the admin interface. It allows specifying a method or property to generate the title, or disabling this feature by setting it to `False`. ```python # Example usage in settings.py (conceptual) # STREAMFIELD_BLOCK_TITLE = 'custom_title_method' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.