Skip to content

Commit

Permalink
Merge branch 'dev' into add-absolute-url-published-content
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud-D committed Aug 26, 2023
2 parents f3a6065 + aaacd06 commit 1cabba7
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 57 deletions.
13 changes: 7 additions & 6 deletions doc/source/front-end/template-tags.rst
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,24 @@ Ce filtre formate une date au format ``DateTime`` destiné à être affiché sur

Ce filtre effectue la même chose que ``format_date`` mais à destination des ``tooltip``.

``humane_time``
---------------
``date_from_timestamp``
-----------------------

Formate une date au format *Nombre de seconde depuis Epoch* en un élément lisible. Ainsi :
Convertit une date au format *Nombre de seconde depuis Epoch* en un objet
accepté par les autres filtres de ce module. Ainsi :

.. sourcecode:: html+django

{% load date %}
{{ date_epoch|humane_time }}
{{ date_epoch|date_from_timestamp|format_date }}

sera rendu :

.. sourcecode:: text

jeudi 01 janvier 1970 à 00h00
jeudi 01 janvier 1970 à 00h02

…si le contenu de ``date_epoch`` était de ``42``.
…si le contenu de ``date_epoch`` était de ``122``.

``from_elasticsearch_date``
---------------------------
Expand Down
4 changes: 2 additions & 2 deletions templates/tutorialv2/view/history.html
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ <h2 class="subtitle">
{% endif %}
</td>
<td>
{{ commit.authored_date|humane_time }}
{{ commit.authored_date|date_from_timestamp|format_date }}
</td>
<td>
<a href="{% url "content:view" content.pk content.slug %}?version={{ commit.hexsha }}" >
Expand Down Expand Up @@ -161,7 +161,7 @@ <h2 class="subtitle">
{% trans "mettre à jour" %}
{% endif %}
{% endcaptureas %}
{% blocktrans with action=action date_version=commit.authored_date|humane_time content_title=content.title %}
{% blocktrans with action=action date_version=commit.authored_date|date_from_timestamp|format_date content_title=content.title %}
Êtes-vous certain de vouloir <strong>{{ action }}</strong> la bêta pour le contenu
"<em>{{ content_title }}</em>" dans sa version de {{ date_version }} ?
{% endblocktrans %}
Expand Down
17 changes: 12 additions & 5 deletions zds/forum/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ class TopicForm(forms.Form, FieldValidatorMixin):
label=_("Tag(s) séparés par une virgule (exemple: python,django,web)"),
max_length=64,
required=False,
widget=forms.TextInput(
attrs={"data-autocomplete": '{ "type": "multiple", "fieldname": "title", "url": "/api/tags/?search=%s" }'}
),
widget=forms.TextInput(),
)

text = forms.CharField(
Expand All @@ -44,6 +42,15 @@ class TopicForm(forms.Form, FieldValidatorMixin):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

self.fields["tags"].widget.attrs.update(
{
"data-autocomplete": '{ "type": "multiple", "fieldname": "title", "url": "'
+ reverse("api:utils:tags-list")
+ '?search=%s" }'
}
)

self.helper = FormHelper()
self.helper.form_class = "content-wrapper"
self.helper.form_method = "post"
Expand All @@ -53,11 +60,11 @@ def __init__(self, *args, **kwargs):
Field("subtitle", autocomplete="off"),
Field("tags"),
HTML(
"""<div id="topic-suggest" style="display:none;" url="/rechercher/sujets-similaires/">
"""<div id="topic-suggest" style="display:none;" url="{}">
<label>{}</label>
<div id="topic-result-container" data-neither="{}"></div>
</div>""".format(
_("Sujets similaires au vôtre :"), _("Aucun résultat")
reverse("search:similar"), _("Sujets similaires au vôtre :"), _("Aucun résultat")
)
),
CommonLayoutEditor(),
Expand Down
31 changes: 31 additions & 0 deletions zds/forum/tests/tests_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.contrib.auth.models import Group
from django.test import TestCase

from zds.forum.tests.factories import create_category_and_forum
from zds.forum.utils import get_authorized_forums_pk
from zds.member.tests.factories import ProfileFactory, StaffProfileFactory


class GetAuthorizedForumsTests(TestCase):
def test_get_authorized_forums_pk(self):
user = ProfileFactory().user
staff = StaffProfileFactory().user

# 1. Create a hidden forum belonging to a hidden staff group:
group = Group.objects.create(name="Les illuminatis anonymes de ZdS")
_, hidden_forum = create_category_and_forum(group)

staff.groups.add(group)
staff.save()

# 2. Create a public forum:
_, public_forum = create_category_and_forum()

# 3. Regular user can access only the public forum:
self.assertEqual(get_authorized_forums_pk(user), [public_forum.pk])

# 4. Staff user can access all forums:
self.assertEqual(sorted(get_authorized_forums_pk(staff)), sorted([hidden_forum.pk, public_forum.pk]))

# 5. By default, only public forums are available:
self.assertEqual(get_authorized_forums_pk(None), [public_forum.pk])
19 changes: 18 additions & 1 deletion zds/forum/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.views.generic import CreateView
from django.views.generic.detail import SingleObjectMixin
from django.utils.translation import gettext as _
from zds.forum.models import Topic, Post
from zds.forum.models import Forum, Topic, Post
from zds.member.views import get_client_ip
from zds.utils.misc import contains_utf8mb4
from zds.utils.mixins import QuoteMixin
Expand Down Expand Up @@ -198,3 +198,20 @@ def post(self, request, *args, **kwargs):

def create_forum(self, form_class, **kwargs):
raise NotImplementedError("`create_forum()` must be implemented.")


def get_authorized_forums_pk(user):
"""
Find forums the user is allowed to visit.
:param user: concerned user.
:return: pk of authorized forums
"""
forums_pub = Forum.objects.filter(groups__isnull=True).all()
if user and user.is_authenticated:
forums_private = Forum.objects.filter(groups__isnull=False, groups__in=user.groups.all()).all()
list_forums = list(forums_pub | forums_private)
else:
list_forums = list(forums_pub)

return [f.pk for f in list_forums]
9 changes: 7 additions & 2 deletions zds/mp/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ class PrivateTopicForm(forms.Form, ParticipantsStringValidator, TitleValidator,
label=_("Participants"),
widget=forms.TextInput(
attrs={
"placeholder": _("Les participants doivent " "être séparés par une virgule."),
"placeholder": _("Les participants doivent être séparés par une virgule."),
"required": "required",
"data-autocomplete": '{ "type": "multiple", "url": "/api/membres/?search=%s" }',
}
),
)
Expand All @@ -40,6 +39,12 @@ class PrivateTopicForm(forms.Form, ParticipantsStringValidator, TitleValidator,

def __init__(self, username, *args, **kwargs):
super().__init__(*args, **kwargs)

self.fields["participants"].widget.attrs.update(
{
"data-autocomplete": '{ "type": "multiple", "url": "' + reverse("api:member:list") + '?search=%s" }',
}
)
self.helper = FormHelper()
self.helper.form_class = "content-wrapper"
self.helper.form_method = "post"
Expand Down
8 changes: 4 additions & 4 deletions zds/searchv2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from zds.searchv2.forms import SearchForm
from zds.searchv2.models import ESIndexManager
from zds.utils.paginator import ZdSPagingListView
from zds.utils.templatetags.authorized_forums import get_authorized_forums
from zds.forum.utils import get_authorized_forums_pk
from functools import reduce


Expand All @@ -38,7 +38,7 @@ def get(self, request, *args, **kwargs):

results = []
if self.index_manager.connected_to_es and self.search_query:
self.authorized_forums = get_authorized_forums(self.request.user)
self.authorized_forums = get_authorized_forums_pk(self.request.user)

search_queryset = Search()
query = (
Expand Down Expand Up @@ -90,7 +90,7 @@ def get(self, request, *args, **kwargs):
excluded_content_ids = request.GET.get("excluded", "").split(",")
results = []
if self.index_manager.connected_to_es and self.search_query:
self.authorized_forums = get_authorized_forums(self.request.user)
self.authorized_forums = get_authorized_forums_pk(self.request.user)

search_queryset = Search()
if len(excluded_content_ids) > 0 and excluded_content_ids != [""]:
Expand Down Expand Up @@ -174,7 +174,7 @@ def get_queryset(self):

if self.search_query:
# Searches forums the user is allowed to visit
self.authorized_forums = get_authorized_forums(self.request.user)
self.authorized_forums = get_authorized_forums_pk(self.request.user)

search_queryset = Search()

Expand Down
37 changes: 23 additions & 14 deletions zds/tutorialv2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,9 +320,7 @@ class EditContentTagsForm(forms.Form):
label=_("Tags séparés par des virgules (exemple : python,api,web) :"),
max_length=64,
required=False,
widget=forms.TextInput(
attrs={"data-autocomplete": '{ "type": "multiple", "fieldname": "title", "url": "/api/tags/?search=%s" }'}
),
widget=forms.TextInput(),
error_messages={"max_length": _("La liste de tags saisie dépasse la longueur maximale autorisée.")},
)

Expand All @@ -331,6 +329,14 @@ def __init__(self, content, db_content, *args, **kwargs):
kwargs["initial"] = {"tags": ", ".join(db_content.tags.values_list("title", flat=True))}
super(forms.Form, self).__init__(*args, **kwargs)

self.fields["tags"].widget.attrs.update(
{
"data-autocomplete": '{ "type": "multiple", "fieldname": "title", "url": "'
+ reverse("api:utils:tags-list")
+ '?search=%s" }',
}
)

self.helper = FormHelper()
self.helper.form_class = "content-wrapper"
self.helper.form_method = "post"
Expand All @@ -341,7 +347,9 @@ def __init__(self, content, db_content, *args, **kwargs):
HTML(
"""<p>Les tags permettent de grouper les publications plus finement que les catégories.
Par exemple, vous pouvez indiquer une technologie ou une sous-discipline.
Consultez <a href="/contenus/tags">la page des tags</a> pour voir des exemples."""
Consultez <a href="{}">la page des tags</a> pour voir des exemples.""".format(
reverse("content:tags")
)
),
Field("tags"),
ButtonHolder(StrictButton("Valider", type="submit")),
Expand Down Expand Up @@ -1302,21 +1310,23 @@ class SearchSuggestionForm(forms.Form):
suggestion_pk = forms.CharField(
label="Contenu à suggérer",
required=False,
widget=forms.TextInput(
attrs={
"data-autocomplete": '{"type": "multiple_checkbox",'
'"limit": 10,'
'"fieldname": "title",'
'"url": "/rechercher/suggestion-contenu/?q=%s&excluded=%e"}',
"placeholder": "Rechercher un contenu",
}
),
widget=forms.TextInput(),
)
excluded_pk = forms.CharField(required=False, widget=forms.HiddenInput(attrs={"class": "excluded_field"}))

def __init__(self, content, *args, **kwargs):
super().__init__(*args, **kwargs)

self.fields["suggestion_pk"].widget.attrs.update(
{
"data-autocomplete": '{"type": "multiple_checkbox",'
'"limit": 10,'
'"fieldname": "title",'
'"url": "' + reverse("search:suggestion") + '?q=%s&excluded=%e"}',
"placeholder": "Rechercher un contenu",
}
)

self.helper = FormHelper()
self.helper.form_action = reverse("content:add-suggestion", kwargs={"pk": content.pk})
self.helper.form_class = "modal modal-large"
Expand All @@ -1326,7 +1336,6 @@ def __init__(self, content, *args, **kwargs):
self.helper.layout = Layout(
Field("suggestion_pk"), Field("excluded_pk"), StrictButton(_("Ajouter"), type="submit")
)
super().__init__(*args, **kwargs)


class RemoveSuggestionForm(forms.Form):
Expand Down
18 changes: 0 additions & 18 deletions zds/utils/templatetags/authorized_forums.py

This file was deleted.

7 changes: 4 additions & 3 deletions zds/utils/templatetags/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ def tooltip_date(value):


@register.filter
def humane_time(timestamp):
"""Render time (number of second from epoch) to an human readable string"""
return format_date(datetime.fromtimestamp(timestamp))
def date_from_timestamp(timestamp):
"""Convert a timestamp (number of second from epoch) to a datetime object,
another filter should then be used to format the datetime object."""
return datetime.fromtimestamp(timestamp)


@register.filter
Expand Down
4 changes: 2 additions & 2 deletions zds/utils/tests/tests_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ def test_tooltip_date(self):
tr = Template("{% load date %}" "{{ NoneVal | tooltip_date }}").render(self.context)
self.assertEqual("None", tr)

def test_humane_time(self):
def test_date_from_timestamp(self):
# Default behaviour
tr = Template("{% load date %}" "{{ date_epoch | humane_time }}").render(self.context)
tr = Template("{% load date %}" "{{ date_epoch | date_from_timestamp | format_date }}").render(self.context)

self.assertEqual(tr, "jeudi 01 janvier 1970 à 01h00")

0 comments on commit 1cabba7

Please sign in to comment.