### Django-DSFR Installation and Configuration Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Sets up Django-DSFR by adding it to INSTALLED_APPS, configuring template context processors, and installing necessary packages. It also includes steps for running migrations and starting the development server. ```python # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', # Required dependency 'dsfr', # Add before your apps 'your_app', ] # For Django 4.2 and earlier, also add: # INSTALLED_APPS.append('django.forms') # FORM_RENDERER = "django.forms.renderers.TemplatesSetting" # Add context processor for site configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'dsfr.context_processors.site_config', # Add this ], }, }, ] # Optional: Enable deprecation warnings DSFR_CHECK_DEPRECATED_PARAMS = True ``` ```bash # Install the package pip install django-dsfr # Run migrations to create configuration models python manage.py migrate # Start development server python manage.py runserver ``` -------------------------------- ### Django: Create Content Cards Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Provides examples for rendering content cards using the dsfr_card tag. Supports basic cards, cards with images and badges, and cards with detailed information and call-to-action buttons. Requires 'dsfr_tags' to be loaded. ```django {% load dsfr_tags %} {# Basic card with title and description #} {% dsfr_card title="Article Title" description="Brief description of the article content." link="/article/1/" %} {# Card with image and badges #} {% dsfr_card title="Featured Content" heading_tag="h3" description="Detailed description with more information about this item." image_url="/static/images/thumbnail.jpg" image_alt="Thumbnail image" ratio_class="fr-ratio-16x9" link="/content/featured/" media_badges=badge_list extra_classes="fr-card--horizontal" %} {# Card with top detail, bottom detail and call-to-action #} {% dsfr_card title="Event Registration" description="Join us for this upcoming event." link="/events/123/" top_detail=top_detail_data bottom_detail=bottom_detail_data call_to_action=cta_buttons %} ``` -------------------------------- ### Rich Radio Button and Form Example (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Defines custom choices for radio buttons with enhanced options like HTML labels and pictograms, and a form using the RichRadioSelect widget for a visually richer user interface. Requires the `django-dsfr` library. ```python from django import forms from django.db.models import IntegerChoices, auto from dsfr.widgets import RichRadioButtonChoices, RichRadioSelect class ServiceChoices(IntegerChoices, RichRadioButtonChoices): SERVICE_A = { 'value': auto(), 'label': 'Service A', 'html_label': 'Service A', 'pictogram': '/static/img/service-a.png', } SERVICE_B = { 'value': auto(), 'label': 'Service B', 'html_label': 'Service B', 'pictogram': '/static/img/service-b.png', } class ServiceSelectionForm(DsfrBaseForm): service = forms.ChoiceField( label="Choose a Service", choices=ServiceChoices.choices, widget=RichRadioSelect(extended_choices=ServiceChoices) ) ``` -------------------------------- ### DSFR Tag and Badge Components Usage (Django Template) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Demonstrates the usage of DSFR's tag and badge components within a Django template. Includes examples for single tags, tags with links, small tags with icons, and various badge styles including system and grouped badges. Requires `dsfr_tags`. ```django {% load dsfr_tags %} {# Single tag #} {% dsfr_tag label="Important" %} {# Tag with link #} {% dsfr_tag label="Category: News" link="/news/" %} {# Small tag with icon #} {% dsfr_tag label="Archived" extra_classes="fr-tag--sm fr-icon-archive-line fr-tag--icon-left" %} {# Badge with color #} {% dsfr_badge label="New" extra_classes="fr-badge--success" %} {# System badge #} {% dsfr_badge label="Warning" extra_classes="fr-badge--warning" %} {# Badge group #} {% dsfr_badge_group items=badges %} ``` -------------------------------- ### List View with Pagination (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt A Django view function that fetches a list of articles, applies pagination using Django's `Paginator` class, and renders the paginated results to a template. It retrieves the current page number from GET parameters. ```python # views.py - List view with pagination from django.core.paginator import Paginator from django.shortcuts import render def article_list(request): articles = Article.objects.all().order_by('-published_date') # Create paginator with 10 items per page paginator = Paginator(articles, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, 'myapp/articles.html', { 'page_obj': page_obj }) ``` -------------------------------- ### Programmatic Site Configuration Creation (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Shows how to programmatically create or update `DsfrConfig` and related models, such as `DsfrSocialMedia`, in a Django application. This is useful for setting initial configurations or managing settings via scripts. Requires the `django-dsfr` models. ```python # Creating/updating configuration programmatically from dsfr.models import DsfrConfig, DsfrSocialMedia # Create French configuration config_fr = DsfrConfig.objects.create( language='fr', site_title='Mon Service Public', site_tagline='Service numérique de l'État', header_brand='République française', header_brand_html='République
française', footer_brand='République française', footer_description='Description du service public.', accessibility_status='PART', # Partially compliant beta_tag=True, # Show BETA badge mourning=False ) ``` -------------------------------- ### Django: Create Accordion Components Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Illustrates how to create single accordion items and accordion groups using dsfr_accordion and dsfr_accordion_group tags. Requires 'dsfr_tags' to be loaded. ```django {% load dsfr_tags %} {# Single accordion item #} {% dsfr_accordion title="Section 1" content="

This is the content of the first section.

" heading_tag="h3" %} {# Accordion group with multiple items #} {% dsfr_accordion_group accordion_items %} ``` -------------------------------- ### Django Template Inheritance and Includes Source: https://github.com/numerique-gouv/django-dsfr/blob/main/example_app/templates/example_app/base.html This snippet demonstrates basic Django template inheritance and the inclusion of reusable components. It extends the 'dsfr/base.html' template and includes header, footer, and newsletter follow components from 'example_app'. ```django {% extends "dsfr/base.html" %} {% load static i18n %} {% block header %} {% include "example_app/blocks/header.html" %} {% endblock header %} {% block footer %} {% include "example_app/blocks/footer.html" %} {% endblock footer %} {% block extra_js %} {% endblock extra_js %} {# djlint:off #} {% block lang %}{% get_current_language as LANGUAGE_CODE %}{{ LANGUAGE_CODE }}{% endblock lang %} {# djlint:on #} {% block follow_newsletter_social_media %} {% include "dsfr/follow.html" %} {% endblock follow_newsletter_social_media %} ``` -------------------------------- ### Django: Create Buttons and Button Groups Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Shows how to render primary, secondary, icon, and disabled buttons using the dsfr_button tag. It also illustrates creating button groups with multiple actions. Requires 'dsfr_tags' to be loaded. ```django {% load dsfr_tags %} {# Primary submit button #} {% dsfr_button label="Submit Form" type="submit" %} {# Secondary button with onclick action #} {% dsfr_button label="Cancel" type="button" onclick="history.back()" extra_classes="fr-btn--secondary" %} {# Disabled button #} {% dsfr_button label="Not Available" is_disabled=True %} {# Button with left icon #} {% dsfr_button label="Download" extra_classes="fr-btn--secondary fr-btn--icon-left fr-icon-download-line" %} {# Button group with multiple buttons #} {% dsfr_button_group items=button_list extra_classes="fr-btns-group--inline-md" %} ``` -------------------------------- ### Site Configuration Model Access (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Provides Python code to access site-wide configuration settings stored in the `DsfrConfig` model. It includes a utility function to retrieve the configuration for the current language, falling back to a default if necessary. Assumes `dsfr.models.DsfrConfig` is available. ```python # models.py - Accessing configuration in views from dsfr.models import DsfrConfig from django.utils.translation import get_language def get_site_config(): """Get site configuration for current language""" config = DsfrConfig.objects.filter(language=get_language()).first() if not config: config = DsfrConfig.objects.first() return config # The context processor automatically provides SITE_CONFIG in templates # templates/myapp/page.html # {{ SITE_CONFIG.site_title }} # {{ SITE_CONFIG.site_tagline }} # {{ SITE_CONFIG.header_brand }} ``` -------------------------------- ### Django Template: Internationalization and License Info Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/footer.html This snippet demonstrates the use of Django's internationalization tags to translate strings and display license information. It includes a link to the license details. ```django {% load i18n %} {% translate "Opens a new window" as new_window_label %} {% translate "etalab-2.0 license" as etalab_license %} {% translate "Unless explicit mention of intellectual property held by third parties, the contents of this site are offered under" %} [{{ etalab_license }}](https://github.com/etalab/licence-ouverte/blob/master/LO.md "{{ etalab_license|capfirst }} - {{ new_window_label }}") {% block footer_bottom_extra %} {% endblock footer_bottom_extra %} ``` -------------------------------- ### Set Up Breadcrumb Navigation Data in Django View Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet illustrates how to prepare data for DSFR breadcrumb navigation within a Django view. It constructs a dictionary containing navigation links, the current page title, and an optional root directory setting. This data is then passed to the template rendering the breadcrumb component. ```python # views.py - Setting up breadcrumb navigation def article_detail(request, category_slug, article_slug): article = get_object_or_404(Article, slug=article_slug) breadcrumb_data = { 'links': [ {'url': '/', 'title': 'Home'}, {'url': f'/category/{category_slug}/', 'title': article.category.name}, ], 'current': article.title, 'root_dir': '' # Set if site is not at domain root } return render(request, 'myapp/article.html', { 'article': article, 'breadcrumb_data': breadcrumb_data }) ``` -------------------------------- ### Service Title and Beta Tag - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Displays the service title in the header, including an optional 'BETA' tag if `SITE_CONFIG.beta_tag` is true. This title also functions as a link to the homepage. ```django {% block service_title %}[{% SITE_CONFIG.site_title }} {% if SITE_CONFIG.beta_tag %} BETA {% endif %} ](/ "Accueil — {{ SITE_CONFIG.site_title }}"){% endblock service_title %} ``` -------------------------------- ### Use Django Messages Framework for Alerts Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Demonstrates the use of Django's messages framework to send different types of messages (success, error, info, warning, debug). These messages can be automatically converted to DSFR alerts. ```python # views.py - Using Django messages framework from django.contrib import messages def process_form(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Your data has been saved successfully.") return redirect('success_page') else: messages.error(request, "Please correct the errors in the form.") # Can also use other message levels messages.info(request, "This is an informational message.") messages.warning(request, "This action cannot be undone.") messages.debug(request, "Debug information for developers.") return render(request, 'myapp/form.html', {'form': form}) ``` -------------------------------- ### DSFR Alert Component Usage Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Shows how to use the `dsfr_alert` template tag to render various types of alerts (info, success, error, warning) with options for titles, content, and collapse functionality. It also demonstrates rendering alerts from Python view context. ```django {% load dsfr_tags %} {# Simple info alert #} {% dsfr_alert title="Information" type="info" content="This is an informational message." %} {# Success alert with HTML content #} {% dsfr_alert title="Success" type="success" content="Your form has been successfully submitted." %} {# Error alert with collapsible close button #} {% dsfr_alert title="Error" type="error" content="An error occurred while processing your request." is_collapsible=True %} {# Small alert without title #} {% dsfr_alert type="warning" content="Brief warning message" extra_classes="fr-alert--sm" %} {# Alert from Python view context #} {# In view: context['alert_data'] = {'title': 'Notice', 'type': 'info', 'content': 'Message'} #} {% dsfr_alert alert_data %} ``` -------------------------------- ### Build Nested Menu Structure for Sidemenu Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Constructs a nested list of dictionaries representing menu items for a sidemenu. This Python code prepares data for the Django template. ```python # views.py - Building nested menu structure def documentation_view(request): menu_items = [ { 'label': 'Getting Started', 'items': [ {'label': 'Installation', 'link': '/docs/installation/'}, {'label': 'Quick Start', 'link': '/docs/quickstart/'}, ] }, { 'label': 'Components', 'items': [ {'label': 'Buttons', 'link': '/docs/components/buttons/'}, {'label': 'Forms', 'link': '/docs/components/forms/'}, {'label': 'Cards', 'link': '/docs/components/cards/'}, ] }, { 'label': 'API Reference', 'link': '/docs/api/' } ] return render(request, 'myapp/docs.html', { 'menu_items': menu_items }) ``` -------------------------------- ### HTML Template for DSFR Search Page Source: https://github.com/numerique-gouv/django-dsfr/blob/main/example_app/templates/example_app/search.html This HTML snippet demonstrates how to structure a search results page using Django template tags. It extends a base template, loads static files, and defines blocks for CSS and JavaScript. The content block displays a search prompt, and the extra_js block contains the client-side JavaScript logic for handling search queries and displaying results. ```html {% extends "example_app/base.html" %} {% load static dsfr_tags %} {% block extra_css %} .alert-hidden { display:none; } {% endblock extra_css %} {% block content %} Recherche ========= Merci de taper votre recherche ci-dessus. {% endblock content %} {% block extra_js %} {% endblock extra_js %} ``` -------------------------------- ### Reference Static Assets using Django Template Tag Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/theme_modale.html The `{% static %}` template tag is used to generate URLs for static files, such as images. This ensures that assets are correctly linked in the HTML, regardless of the deployment configuration. Images for theme selection (light, dark, system) are referenced this way. ```django {% load static i18n %} ![]({% static 'dsfr/dist/artwork/light.svg' %}) ![]({% static 'dsfr/dist/artwork/dark.svg' %}) ![]({% static 'dsfr/dist/artwork/system.svg' %}) ``` -------------------------------- ### Build Accordion Groups with Django View Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet demonstrates how to create an accordion component in a Django view. It defines a list of items, each with an ID, title, content, and heading tag, which are then passed to a template for rendering. No external dependencies beyond Django are required. ```python def faq_view(request): context = { 'accordion_items': [ { 'id': 'faq-1', 'title': 'What is this service?', 'content': '

This service provides access to government information and services.

', 'heading_tag': 'h3', }, { 'id': 'faq-2', 'title': 'How do I register?', 'content': '

You can register by clicking the registration button and filling out the form.

', 'heading_tag': 'h3', }, { 'id': 'faq-3', 'title': 'Who can use this service?', 'content': '

This service is available to all French citizens and residents.

', 'heading_tag': 'h3', } ] } return render(request, 'myapp/faq.html', context) ``` -------------------------------- ### Header Tools Links - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Defines a list of tool links for the header, such as 'Créer un espace', 'Se connecter', and 'S’enregistrer'. The URLs are placeholders and need to be modified. ```django {% block header_tools %}* [Créer un espace]([url - à modifier]) * [Se connecter]([url - à modifier]) * [S’enregistrer]([url - à modifier]) {% endblock header_tools %} ``` -------------------------------- ### Python: Prepare Button Group Data for Django Template Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This Python view prepares a list of dictionaries, where each dictionary represents a button for a button group. This data is then passed to the Django template for rendering. ```python from django.shortcuts import render def form_view(request): context = { 'button_list': [ { 'label': 'Save Draft', 'name': 'action', 'type': 'submit', 'extra_classes': 'fr-btn--secondary', }, { 'label': 'Submit', 'name': 'action', 'type': 'submit', }, { 'label': 'Cancel', 'type': 'button', 'onclick': 'window.location.href="/";', 'extra_classes': 'fr-btn--tertiary', } ] } return render(request, 'myapp/form.html', context) ``` -------------------------------- ### Main Menu Translation and Links - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Renders the main navigation menu. It includes a 'Close' button and uses translated labels for the menu. The menu items are placeholder links that need to be updated. ```django {% block main_menu %} {% translate "Close" %} {% translate "Main menu" as main_menu_label %} * [accès direct](#) * [accès direct](#) * [accès direct](#) * [accès direct](#) {% endblock main_menu %} ``` -------------------------------- ### Add Social Media Links Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Creates new social media links associated with a site configuration. Requires Django ORM and a 'config_fr' object. ```python DsfrSocialMedia.objects.create( site_config=config_fr, title='Twitter', url='https://twitter.com/example', icon_class='fr-icon-twitter-line' ) DsfrSocialMedia.objects.create( site_config=config_fr, title='LinkedIn', url='https://linkedin.com/company/example', icon_class='fr-icon-linkedin-line' ) ``` -------------------------------- ### Render DSFR Tile Component in Django Templates Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/tile.html This snippet illustrates the structure for rendering a DSFR tile component within Django templates. It includes logic for displaying a title, optional description, details, and either tags or badges. ```django {% load dsfr_tags %} <{{ self.heading_tag | default:"h3" }} class="fr-tile__title"> [{{ self.title }}]({{ self.url }}) {% if self.description %} {{ self.description }} {% endif %} {% if self.detail %} {{ self.detail }} {% endif %} {% if self.top_detail %} {% if self.top_detail.tags %} {% for tag in self.top_detail.tags %}* {% dsfr_tag tag %} {% endfor %} {% elif self.top_detail.badges %} {% for badge in self.top_detail.badges %}* {% dsfr_badge badge %} {% endfor %} {% endif %} {% endif %} {% if self.svg_path %} {% else %} ![]({{ self.image_path }}) {% endif %} ``` -------------------------------- ### Display Quote and Highlight Components Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Renders DSFR quote and highlight components using Django template tags. Supports various attributes for customization like author, source, image, and color classes. ```django {% load dsfr_tags %} {# Simple quote #} {% dsfr_quote text="This is an important statement from a government official." author="Jean Dupont" source="Ministry of Example" %} {# Quote with source URL and image #} {% dsfr_quote text="Quote text here" author="Minister Name" source="Official Statement" source_url="https://example.gouv.fr/statement" image_url="/static/img/minister.jpg" extra_classes="fr-quote--green-emeraude" %} {# Highlight important text #} {% dsfr_highlight content="Important: This service will be unavailable on January 20th." size_class="fr-text--lg" %} {# Colored highlight #} {% dsfr_highlight content="New feature available" extra_classes="fr-highlight--green-emeraude" %} ``` -------------------------------- ### Create Sidemenu Navigation Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Generates a hierarchical sidemenu navigation component using DSFR template tags. Requires 'dsfr_tags' and a 'menu_items' list. ```django {% load dsfr_tags %} {% dsfr_sidemenu title="Documentation" items=menu_items extra_classes="fr-sidemenu--sticky" %} ``` -------------------------------- ### Manage Multi-step Form with Stepper Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Manages multi-step form data and provides information for the DSFR stepper component. This Python view prepares step data and renders the appropriate form. ```python # views.py - Multi-step form with stepper def registration_step(request, step): steps = [ {'id': 1, 'title': 'Account Creation', 'form': AccountForm}, {'id': 2, 'title': 'Personal Information', 'form': PersonalInfoForm}, {'id': 3, 'title': 'Address Details', 'form': AddressForm}, {'id': 4, 'title': 'Confirmation', 'form': None}, ] current = steps[step - 1] next_step = steps[step] if step < len(steps) else None stepper_data = { 'current_step_id': current['id'], 'current_step_title': current['title'], 'next_step_title': next_step['title'] if next_step else None, 'total_steps': len(steps) } return render(request, 'myapp/registration.html', { 'stepper_data': stepper_data, 'form': current['form']() if current['form'] else None }) ``` -------------------------------- ### Base Template Integration with DSFR Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Demonstrates how to extend the DSFR base template in a Django project to include custom headers and footers. It utilizes Django template tags and DSFR specific tags for rendering. ```django {# templates/myapp/base.html #} {% extends "dsfr/base.html" %} {% load static dsfr_tags %} {% block title %}My Government Service{% endblock %} {% block header %} {% endblock header %} {% block content %}

Welcome to My Service

{% dsfr_alert title="Information" type="info" content="This is a government service." %}
{% endblock content %} {% block footer %} {% endblock footer %} ``` -------------------------------- ### Django Template: Footer Brand Rendering Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/footer.html This snippet renders the brand information in the footer, including an operator logo if configured. It handles linking to the homepage and displays site-specific branding. ```django {% load i18n %} {% translate "Back to home page" as back_to_home_label %} {% if SITE_CONFIG.operator_logo_file and SITE_CONFIG.operator_logo_alt %} {{ SITE_CONFIG.footer_brand_html| default_if_none:'république française' | safe }} [![{{ SITE_CONFIG.operator_logo_alt }}]({{ SITE_CONFIG.operator_logo_file.url }})= 1 %}style="max-width:{{ SITE_CONFIG.operator_logo_width }}rem;"{% endif %} /> {# L’alternative de l’image (attribut alt) doit impérativement être renseignée et reprendre le texte visible dans l’image #}](/ "{{ back_to_home_label }} - {{ SITE_CONFIG.operator_logo_alt }} - {{ SITE_CONFIG.footer_brand|default:'république française' }}") {% else %} [{% block brand %} {{ SITE_CONFIG.footer_brand_html| default_if_none:'république française' | safe }} {% endblock brand %](/ "{{ back_to_home_label }} - {{ SITE_CONFIG.site_title }} - {{ SITE_CONFIG.footer_brand|default:'république française' }}") {% endif %} {% endblock footer_brand %} ``` -------------------------------- ### JavaScript Search Functionality with Fuse.js Source: https://github.com/numerique-gouv/django-dsfr/blob/main/example_app/templates/example_app/search.html This JavaScript code implements a client-side search feature using the Fuse.js library. It takes a search query from the URL parameters, fetches search data from a JSON file, and filters results based on a score threshold. The results are then displayed as a list of links. It includes a helper function for pluralizing words. ```javascript const pluralize = (count, noun, suffix = 's') => `${count} ${noun}${count !== 1 ? suffix : ''}`; let fuseOptions = { shouldSort: true, includeScore: true, keys: [ {name:"title",weight:0.8}, {name:"text",weight:0.5}, ] }; let params = new URLSearchParams(window.location.search); let query = params.get('q') if (!query) { const NoQueryAlert = document.getElementById("no-query"); NoQueryAlert.classList.remove("alert-hidden"); } else { const ResultsDiv = document.getElementById("results"); fetch("{% static 'json/search_data.json' %}") .then((response) => response.json()) .then((search_data) => { const fuse = new Fuse(search_data, fuseOptions); let results = fuse.search(query); // Filter results with too bad a score (perfect score = 0, worst = 1) results = results.filter((r) => r.score < 0.7); if ( results.length) { let ResultsDivTemp = "

" + pluralize(results.length, "résultat") + " pour la recherche « " + query + " »

"; } else { ResultsDiv.innerHTML = "

Aucun résultat trouvé

"; } }); } ``` -------------------------------- ### Integrate Forms with Django DSFR Base Form and Templates Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet demonstrates creating DSFR-styled forms in Django using `DsfrBaseForm` and rendering them in templates. It covers rendering the entire form, individual fields using `dsfr_form_field`, displaying Django messages as DSFR alerts, and using `dsfr_button_group` for submission. The `dsfr_tags` must be loaded. ```django {# templates/myapp/form.html #} {% load dsfr_tags %}
{% csrf_token %} {# Render entire form with DSFR styling #} {{ form }} {# Or render individual fields with dsfr_form_field #} {% dsfr_form_field form.username %} {% dsfr_form_field form.email %} {% dsfr_form_field form.message %} {# Display Django messages as DSFR alerts #} {% dsfr_django_messages is_collapsible=True %} {% dsfr_button_group items=submit_buttons %}
``` -------------------------------- ### Django Template: Footer Links Generation Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/footer.html This snippet generates various links for the footer, including sitemap, accessibility status, legal notice, personal data, and cookie management. It utilizes Django's URL tag for dynamic link generation. ```django {% load i18n %} {% block footer_links %}* {% url 'footer-sitemap' as sitemap_url %} [{% translate "Sitemap" %}]({% %}) * {% url 'footer-accessibility-status' as accessibility_status_url %} [{% with accessibility_status=SITE_CONFIG.get_accessibility_status_display|default:"non" %} {% blocktranslate %}Accessibility: {{ accessibility_status }} compliant{% endblocktranslate %} {% endwith %}]({% %}) * {% url 'footer-legal-notice' as legal_notice_url %} [{% translate "Legal notice" %}]({% %}) * {% url 'footer-personal-data' as personal_data_url %} [{% translate "Personal data" %}]({% %}) * {% url 'footer-cookie-management' as cookie_management_url %} [{% translate "Cookie management" %}]({% %}) {% endblock footer_links %} ``` -------------------------------- ### Creating Tag and Badge Data (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt A Django view function that prepares data for DSFR tags and badges, typically for displaying article-specific information like status and view counts. The data is structured as a list of dictionaries, suitable for passing to template tags like `dsfr_badge_group`. ```python # views.py - Creating tag and badge collections def article_detail(request, slug): article = get_object_or_404(Article, slug=slug) badges = [ {'label': article.status, 'extra_classes': 'fr-badge--success'}, {'label': f'{article.view_count} views', 'extra_classes': 'fr-badge--info fr-badge--sm'}, ] context = { 'article': article, 'badges': badges } return render(request, 'myapp/article.html', context) ``` -------------------------------- ### Display Stepper Component Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Renders a DSFR stepper component to indicate progress in a multi-step process. Requires the current step ID, title, next step title, and total number of steps. ```django {% load dsfr_tags %} {% dsfr_stepper current_step_id=2 current_step_title="Personal Information" next_step_title="Address Details" total_steps=4 heading_tag="h2" %} ``` -------------------------------- ### Python: Prepare Complex Card Data for Django Template Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This Python view constructs a complex data structure for a card component, including badges, top details with icons and tags, bottom details, and call-to-action buttons. It also specifies an image ratio. ```python from dsfr.constants import IMAGE_RATIOS from django.shortcuts import render def event_list(request): context = { 'badge_list': [ {'label': 'New', 'extra_classes': 'fr-badge--success'}, {'label': 'Featured', 'extra_classes': 'fr-badge--info'}, ], 'top_detail_data': { 'detail': { 'text': 'Published on 2024-01-15', 'icon_class': 'fr-icon-calendar-line' }, 'tags': [ {'label': 'Education'}, {'label': 'Technology'}, ] }, 'bottom_detail_data': { 'text': 'Location: Paris', 'icon_class': 'fr-icon-map-pin-line' }, 'cta_buttons': [ { 'label': 'Register Now', 'onclick': 'register()', 'extra_classes': 'fr-btn--sm' } ], 'ratio': IMAGE_RATIOS['16x9'] } return render(request, 'myapp/events.html', context) ``` -------------------------------- ### DSFR Pagination Component Integration (Django Template) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Integrates the DSFR pagination component into a Django template to provide navigation for list views. It requires the `dsfr_tags` to be loaded and uses `page_obj` passed from the view context. Assumes `page_obj` is a Django Paginator object. ```django {% load dsfr_tags %}
{% for item in page_obj %} {# Display items #}
{{ item.title }}
{% endfor %} {# DSFR pagination component #} {% dsfr_pagination page_obj %}
``` -------------------------------- ### Form Submission Handling with Messages (Python) Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt A Django view function demonstrating how to handle POST requests for a form, process valid data, and display success or error messages to the user using Django's messaging framework. Assumes a `ContactForm` is defined elsewhere. ```python # views.py - Handling form submission with messages from django.contrib import messages from django.shortcuts import render, redirect def contact_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process form data name = form.cleaned_data['name'] email = form.cleaned_data['email'] # ... handle submission ... messages.success(request, f"Thank you {name}, your message has been received.") return redirect('contact_success') else: messages.error(request, "Please correct the errors below.") else: form = ContactForm() context = { 'form': form, 'submit_buttons': [ {'label': 'Send Message', 'type': 'submit'}, {'label': 'Clear', 'type': 'reset', 'extra_classes': 'fr-btn--secondary'} ] } return render(request, 'myapp/contact.html', context) ``` -------------------------------- ### Django: Pass Alert Data to Template Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Demonstrates how to pass alert data from a Django view to a template. The 'alert_data' dictionary contains properties like title, type, content, and collapsibility. ```python from django.shortcuts import render def my_view(request): context = { 'alert_data': { 'title': 'Processing Complete', 'type': 'success', 'content': 'Your data has been saved successfully.', 'is_collapsible': True, } } return render(request, 'myapp/page.html', context) ``` -------------------------------- ### Django Template: External Links in Footer Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/footer.html This snippet displays a list of external government resource links within the footer. Each link is configured to open in a new window with specific tooltip text. ```django {% load i18n %} {% translate "Opens a new window" as new_window_label %} * [info.gouv.fr](https://www.info.gouv.fr "info.gouv.fr - {{ new_window_label }}") * [service-public.gouv.fr](https://service-public.gouv.fr "service-public.gouv.fr - {{ new_window_label }}") * [legifrance.gouv.fr](https://legifrance.gouv.fr "legifrance.gouv.fr - {{ new_window_label }}") * [data.gouv.fr](https://data.gouv.fr "data.gouv.fr - {{ new_window_label }}") ``` -------------------------------- ### Render Operator Logo - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Displays the operator's logo in the header if configured. It checks for `SITE_CONFIG.operator_logo_file` and `SITE_CONFIG.operator_logo_alt`. The logo's maximum width can also be controlled via `SITE_CONFIG.operator_logo_width`. ```django {% block operator_logo %} {% if SITE_CONFIG.operator_logo_file and SITE_CONFIG.operator_logo_alt %} ![{{ SITE_CONFIG.operator_logo_alt }}]({{ SITE_CONFIG.operator_logo_file.url }})= 1 %}style="max-width:{{ SITE_CONFIG.operator_logo_width }}rem;"{% endif %} /> {% endif %} {% endblock operator_logo %} ``` -------------------------------- ### Render DSFR Tag in Django Templates Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/tile.html This snippet demonstrates how to load and use the 'dsfr_tag' template tag within a Django project. It's used to render a single DSFR tag component, typically used for categorization or highlighting. ```django {% load dsfr_tags %} {% dsfr_tag tag %} ``` -------------------------------- ### Service Tagline Display - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Renders the service tagline below the service title in the header. It directly uses the `SITE_CONFIG.site_tagline` variable. ```django {% block service_tagline %} {{ SITE_CONFIG.site_tagline }} {% endblock service_tagline %} ``` -------------------------------- ### Prepare Table Data for Django DSFR View Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet shows a Django view preparing data for a DSFR-styled table. It defines a list for table headers and a list of lists for the table content, which are then passed to the template. This structure is compatible with the `dsfr_table` template tag. ```python # views.py - Building table data def statistics_view(request): context = { 'table_headers': ['Name', 'Email', 'Status', 'Last Login'], 'table_data': [ ['Jean Dupont', 'jean.dupont@example.fr', 'Active', '2024-01-15'], ['Marie Martin', 'marie.martin@example.fr', 'Active', '2024-01-14'], ['Pierre Durand', 'pierre.durand@example.fr', 'Inactive', '2023-12-20'], ] } return render(request, 'myapp/statistics.html', context) ``` -------------------------------- ### Implement Breadcrumb Navigation with Django Templates Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet shows how to implement DSFR-styled breadcrumb navigation using Django template tags. It supports passing breadcrumb data either directly as a context variable or as a dictionary parameter to the `dsfr_breadcrumb` tag. The `dsfr_tags` must be loaded in the template. ```django {% load dsfr_tags %} {# Breadcrumb from context variable #} {% dsfr_breadcrumb breadcrumb_data %} {# Or pass directly as parameter #} {% dsfr_breadcrumb data_dict %} ``` -------------------------------- ### Configure Custom Django Message Tag Mapping Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt Defines a custom mapping in Django settings to associate message levels with specific CSS classes for DSFR alerts. This allows fine-grained control over alert styling. ```python # settings.py - Custom message type mapping from django.contrib import messages DSFR_MESSAGE_TAGS_CSS_CLASSES = { messages.DEBUG: 'info', messages.INFO: 'info', messages.SUCCESS: 'success', messages.WARNING: 'warning', messages.ERROR: 'error', 50: 'error', # Custom fatal level maps to error } ``` -------------------------------- ### Django Forms: Custom Radio/Checkbox Help Text and Inline Layout Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/form_base.html This Django comment provides guidance on how to customize radio buttons and multiple checkboxes within Django forms for DSFR integration. It explains how to add help text under each option and how to render them in a horizontal list using widget attributes. ```python # Radio button and multiple checkboxes : -Help text under each button/checkbox : In your forms.py, in the ChoiceField or MultipleChoiceField, instead of choices=(("a", "label a"), ("b", "label b"), ...), put choices=(("a", {"label":"label a", "help_text":"help text a"}), ("b", {"label":"label b", "help_text":"help text b"})), -Horizontal list of buttons/checkboxes : In your forms.py, in the RadioSelect widget or the CheckboxSelectMultiple widget, put attrs={"class":"fr-fieldset--inline"} ``` -------------------------------- ### Display Tables with Django DSFR Template Tags Source: https://context7.com/numerique-gouv/django-dsfr/llms.txt This snippet demonstrates using the `dsfr_table` Django template tag to render data in DSFR-styled tables. It supports basic table structures and tables with custom classes for additional styling like borders and larger sizes. The `dsfr_tags` must be loaded. ```django {% load dsfr_tags %} {# Basic table #} {% dsfr_table caption="User Statistics" header=table_headers content=table_data %} {# Table with custom styling #} {% dsfr_table caption="Financial Report" header=headers content=data extra_classes="fr-table--bordered fr-table--lg" %} ``` -------------------------------- ### Render DSFR Badge in Django Templates Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/tile.html This snippet shows the usage of the 'dsfr_badge' template tag in Django. It's designed to render DSFR badge components, often used to display status or key information. ```django {% load dsfr_tags %} {% dsfr_badge badge %} ``` -------------------------------- ### Translate Text using Django Template Tag Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/theme_modale.html The `{% translate %}` template tag from Django's i18n framework is used to mark strings for translation. This allows the application to support multiple languages by providing translated versions of user-facing text. ```django {% load static i18n %} {% translate "Close" %} {% translate "Display settings" %} {% translate "Choose a theme to customize the appearance of the site." %} {% translate "Light theme" %} {% translate "Dark theme" %} {% translate "System" %} {% translate "Uses system settings." %} ``` -------------------------------- ### Display Republic Brand - Django Template Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/header.html Renders the 'République Française' brand in the header. It uses the `SITE_CONFIG.header_brand_html` variable, falling back to a default string if not provided. The `safe` filter is used to render HTML content directly. ```django {% load i18n %} {% block brand %} {{ SITE_CONFIG.header_brand_html|default_if_none:"république française" | safe }} {% endblock brand %} ``` -------------------------------- ### Django Template: Form Structure with DSFR Blocks Source: https://github.com/numerique-gouv/django-dsfr/blob/main/dsfr/templates/dsfr/form_base.html A base Django template structure for rendering forms using DSFR components. It defines various blocks (e.g., `before_form`, `head_form`, `foot_form`, `after_form`) to allow for customization and insertion of additional content before, during, or after the form fields. ```html {% extends "dsfr/base.html" %}{% load static dsfr_tags widget_tweaks %}{% block extra_css %}{% endblock extra_css %}{% block content %}{# Everything that needs to be outside the form, before #}{% block before_form %}{% endblock before_form %}{% csrf_token %}{# Everything that needs to be in the form but before the fields (form title for example) #}{% block head_form %}{% endblock head_form %}{# If you need to add formsets before the form #}{% block extra_formset_before %}{% endblock extra_formset_before %}{# The fields #}{% for field in form.visible_fields %}{# Everything that needs to be in the for loop #}{% block inside_form %}{% endblock inside_form %}{% include "dsfr/form_field_snippets/field_snippet.html" %}{% endfor %}{# If you need to add formsets after the form #}{% block extra_formset_after %}{% endblock extra_formset_after %}{# Everything that needs to be in the form but after the fields (the buttons for example) #}{% block foot_form %}{% endblock foot_form %}{# Everything that needs to be outside the form, after #}{% block after_form %}{% endblock after_form %}{% endblock content %} ```