Skip to content

Commit

Permalink
Amélioration des formulaires (#164)
Browse files Browse the repository at this point in the history
* dsfr_form: Add deprecation warning

* Update formsets

* Missing translation

* Update messages

* Remove obsolete file

* Improve documentation and fix example uses

* Improve warnings

* Consistency

* Add deprecation warning in the README file
  • Loading branch information
Ash-Crow authored Aug 20, 2024
1 parent 211047a commit 0e2ca80
Show file tree
Hide file tree
Showing 20 changed files with 124 additions and 67 deletions.
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Note: Only supported versions of Django and Python are supported by this project
- `Python <https://devguide.python.org/versions/>`_
- `Django <https://www.djangoproject.com/download/#supported-versions>`_

Warning: Support for Django < 4.0 and Python < 3.10 will be removed at the end of 2024.

Quick start
-----------

Expand Down
10 changes: 8 additions & 2 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pathlib import Path
import os
from django import VERSION as DJANGO_VERSION
import warnings

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Expand All @@ -28,6 +29,13 @@

ALLOWED_HOSTS = []

warnings.simplefilter("default")
if DJANGO_VERSION < (4, 0):
warnings.warn(
"Support for Django < 4.0 will be deprecated in django-dsfr at the end of 2024.",
PendingDeprecationWarning,
stacklevel=3,
)

# Application definition

Expand Down Expand Up @@ -125,8 +133,6 @@

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGES = [
Expand Down
19 changes: 5 additions & 14 deletions doc/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,8 @@ def __init__(self, *args, **kwargs):
self.fields["password"].widget.attrs["class"] += " my custom class"
```

## Utilisation avec les `Formsets`

La balise `{% dsfr_form %}` prend un paramètre optionnel `form` qui permet de surcharger le formulaire à rendre, ce qui est pratique lors de l'utilisation de `Formsets` :

```{ .django }
<form method="post">
{{ formset.management_form }}
<table>
{% for subform in formset %}
{% dsfr_form subform %}
{% endfor %}
</table>
</form>
```
## Utilisation

La balise `{% dsfr_form %}` est maintenant dépréciée et sera retirée à la fin de l’année 2024.

Il faut donc remplacer les instances de `{% dsfr_form %}` par ``{{ form }}`` et `{% dsfr_form my_custom_form %}` par `{{ my_custom_form }}`.
8 changes: 5 additions & 3 deletions dsfr/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,21 @@ def engine(self):
"APP_DIRS": True,
"DIRS": [
Path(__file__).resolve().parent / self.backend.app_dirname,
Path(forms.__path__[0]).resolve() / "templates",
Path(forms.__path__[0]).resolve() / "templates", # type: ignore
],
"NAME": "djangoforms",
"OPTIONS": {},
}
} # type: ignore
)


class DsfrBaseForm(Form):
"""
A base form that adds the necessary class on relevant fields
A base form that adds the necessary classes on relevant fields
"""

template_name = "dsfr/form_snippet.html" # type: ignore

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
Expand Down
Binary file modified dsfr/locale/fr/LC_MESSAGES/django.mo
Binary file not shown.
8 changes: 4 additions & 4 deletions dsfr/locale/fr/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-08-13 14:26+0200\n"
"PO-Revision-Date: 2024-08-13 14:27+0200\n"
"POT-Creation-Date: 2024-08-19 12:48+0200\n"
"PO-Revision-Date: 2024-08-19 12:48+0200\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: fr\n"
Expand Down Expand Up @@ -310,11 +310,11 @@ msgstr ""
"Sauf mention explicite de propriété intellectuelle détenue par des tiers, "
"les contenus de ce site sont proposés sous"

#: dsfr/templates/dsfr/formset_base.html:27
#: dsfr/templates/dsfr/formset_base.html:31
msgid "Delete this item"
msgstr "Supprimer cet élément"

#: dsfr/templates/dsfr/formset_base.html:37
#: dsfr/templates/dsfr/formset_base.html:39
msgid "Add an item"
msgstr "Ajouter un élément"

Expand Down
32 changes: 17 additions & 15 deletions dsfr/templates/dsfr/formset_base.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
{% block formset_title %}
{% endblock formset_title %}
{% for form in formset %}
<div class="{% cycle 'row1' 'row2' %} formset-row-{{ formset.prefix }} formset"
<div class="{% cycle 'row1' 'row2' %} formset-row-{{ formset.prefix }} formset {% block formset_style %}fr-background-alt--grey fr-px-6v fr-py-6v fr-mb-4v{% endblock formset_style %}"
id="formset-0">
{% for hidden in form.hidden_fields %}
{{ hidden }}
Expand All @@ -24,21 +24,23 @@
{% include "dsfr/form_field_snippets/field_snippet.html" %}
{% endfor %}
<div class="fr-mt-2w">
<a id="remove-0" href="#" onclick="removeFormset(0)">{% translate "Delete this item" %} <span class="fr-fi-delete-line" aria-hidden="true"></span>
<br />
<br />
</a>
</div>
<button id="remove-0"
type="button"
class="fr-btn fr-btn--secondary fr-fi-delete-line fr-btn--icon-right fr-mt-1w"
onclick="removeFormset(0)">
{% translate "Delete this item" %}
</button>
</div>
</div>
{% endfor %}
<button id="add-form"
type="button"
class="fr-btn fr-btn--secondary fr-fi-add-circle-line fr-btn--icon-right fr-mt-1w">
{% translate "Add an item" %}
</button>
</div>
{% endfor %}
<button id="add-form"
type="button"
class="fr-btn fr-btn--secondary fr-fi-add-circle-line fr-btn--icon-right fr-mt-1w">
{% translate "Add an item" %}
</button>
</div>
<br />
{% endif %}
<br />
{% endif %}
{% endblock form_set %}
{% block extra_js %}
<script type="text/javascript">let objectName = "{{ object_name }}";</script>
Expand Down
29 changes: 21 additions & 8 deletions dsfr/templatetags/dsfr_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,15 @@

register = template.Library()

warnings.simplefilter("default")

# Check for obsolete parameters inside tags?
# Deprecated tags will always issue a warning
if (
hasattr(settings, "DSFR_CHECK_DEPRECATED_PARAMS")
and settings.DSFR_CHECK_DEPRECATED_PARAMS
):
CHECK_DEPRECATED = True
CHECK_DEPRECATED_PARAMS = True
else:
CHECK_DEPRECATED = False
CHECK_DEPRECATED_PARAMS = False

"""
Tags used in the "DSFR" templates.
Expand Down Expand Up @@ -1154,7 +1152,7 @@ def dsfr_table(*args, **kwargs) -> dict:
]
tag_data = parse_tag_args(args, kwargs, allowed_keys)

if "extra_classes" in tag_data and CHECK_DEPRECATED:
if "extra_classes" in tag_data and CHECK_DEPRECATED_PARAMS:
extra_classes = tag_data["extra_classes"]
# Deprecated in DSFR 1.12
deprecated_layout_classes = [
Expand All @@ -1168,7 +1166,7 @@ def dsfr_table(*args, **kwargs) -> dict:
warnings.warn(
f"Due to changes in the DSFR v1.12, class {dc} is deprecated in django-dsfr v1.3 or superior",
DeprecationWarning,
stacklevel=2,
stacklevel=3,
)

# Deprecated in DSFR 1.12
Expand Down Expand Up @@ -1558,11 +1556,18 @@ def _render_alert_tag(message):
@register.inclusion_tag("dsfr/form_snippet.html", takes_context=True)
def dsfr_form(context: Context, form=None) -> dict:
"""
Returns the HTML for a form snippet
Returns the HTML for a form snippet.
<div role="alert" class="fr-alert fr-alert--warning">
<h3 class="fr-alert__title">This tag is obsolete and it will be removed at the end of 2024.</h3>
<p>
Please directly include the form with <code>{{ form }}</code> (or the name of the form context variable if different).
</p>
</div>
```python
data_dict = {
"form": an optionnal form to render instead of the form already present in context
"form": an optional form to render instead of the form already present in context
}
```
Expand All @@ -1572,6 +1577,14 @@ def dsfr_form(context: Context, form=None) -> dict:
**Usage**:
`{% dsfr_form %}`
""" # noqa

warnings.warn(
"""The dsfr_form tag is deprecated and will be removed from django-dsfr at the end of 2024.
Please use a normal {{ form }} tag (requires Django 4 or superior)""",
DeprecationWarning,
stacklevel=2,
)

return context.update({"form": form}) if form else context # type: ignore


Expand Down
4 changes: 2 additions & 2 deletions example_app/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def __init__(self, *args, **kwargs):
class AuthorCreateForm(ModelForm, DsfrBaseForm):
class Meta:
model = Author
exclude = []
exclude = [] # NOSONAR
widgets = {
"first_name": forms.TextInput(),
"last_name": forms.TextInput(),
Expand All @@ -159,7 +159,7 @@ class Meta:
class BookCreateForm(ModelForm, DsfrBaseForm):
class Meta:
model = Book
exclude = []
exclude = [] # NOSONAR
widgets = {
"title": forms.TextInput(),
"number_of_pages": forms.NumberInput(),
Expand Down
Binary file modified example_app/locale/fr/LC_MESSAGES/django.mo
Binary file not shown.
14 changes: 7 additions & 7 deletions example_app/locale/fr/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-08-13 14:26+0200\n"
"PO-Revision-Date: 2024-08-13 14:46+0200\n"
"POT-Creation-Date: 2024-08-19 12:48+0200\n"
"PO-Revision-Date: 2024-08-19 12:48+0200\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: fr\n"
Expand All @@ -34,7 +34,7 @@ msgstr "Nom"
msgid "Birth date"
msgstr "Date de naissance"

#: example_app/models.py:18
#: example_app/models.py:18 example_app/models.py:47
msgid "Author"
msgstr "Auteur"

Expand Down Expand Up @@ -62,19 +62,19 @@ msgstr "Papier"
msgid "Digital"
msgstr "Numérique"

#: example_app/models.py:45
#: example_app/models.py:49
msgid "Title"
msgstr "Titre"

#: example_app/models.py:46
#: example_app/models.py:50
msgid "Number of pages"
msgstr "Nombre de pages"

#: example_app/models.py:48
#: example_app/models.py:52
msgid "Format"
msgstr "Format"

#: example_app/models.py:53
#: example_app/models.py:57
msgid "Book"
msgstr "Livre"

Expand Down
23 changes: 23 additions & 0 deletions example_app/migrations/0003_alter_book_author.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.2.15 on 2024-08-19 10:47

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
("example_app", "0002_alter_author_options_alter_book_options_and_more"),
]

operations = [
migrations.AlterField(
model_name="book",
name="author",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="example_app.author",
verbose_name="Author",
),
),
]
6 changes: 5 additions & 1 deletion example_app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ class Meta:

class Book(models.Model):
author = models.ForeignKey(
Author, on_delete=models.CASCADE, null=False, blank=False
Author,
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name=_("Author"),
)
title = models.CharField(_("Title"), max_length=250, null=False, blank=False)
number_of_pages = models.CharField(_("Number of pages"), max_length=6, blank=True)
Expand Down
8 changes: 8 additions & 0 deletions example_app/templates/example_app/doc_markdown.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{% extends "example_app/base.html" %}
{% load static dsfr_tags %}

{% block content %}
<h1>
{{ title }}
Expand All @@ -13,6 +14,13 @@ <h1>
</div>
{{ documentation|safe }}
{% endblock content %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/dsfr-code.css' %}">
<style>
p code, li code {
background: var(--background-alt-grey);
padding: 0.2em;
}
</style>
{% endblock extra_css %}
4 changes: 2 additions & 2 deletions example_app/templates/example_app/page_colors.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ <h2>
Couleurs de fond
</h2>
<form class="fr-mb-4w">
{% dsfr_form full_color_form %}
{{ full_color_form }}
</form>
<p>
Il est possible de changer la couleur de fond d’un paragraphe ou d’une div. Les couleurs primaires, neutres et illustratives sont prises en compte.
Expand Down Expand Up @@ -85,7 +85,7 @@ <h2>
Certains composants prennent une couleur d’accentuation comme paramètre. Seules les couleurs illustratives sont prises en compte.
</p>
<form class="fr-mb-4w">
{% dsfr_form accent_color_form %}
{{ accent_color_form }}
</form>
<div class="example-use">
<h3>
Expand Down
9 changes: 5 additions & 4 deletions example_app/templates/example_app/page_component.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
font-family: monospace;
font-size: 1rem;
}
p code, li code {
background: var(--background-alt-grey);
padding: 0.2em;
}

p code, li code {
background: var(--background-alt-grey);
padding: 0.2em;
}
</style>
{% endblock extra_css %}

Expand Down
Loading

0 comments on commit 0e2ca80

Please sign in to comment.