Skip to content

Commit

Permalink
Ajoute le formulaire pour modifier la miniature
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud-D committed May 8, 2024
1 parent 7120ad1 commit af7998a
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 90 deletions.
1 change: 1 addition & 0 deletions templates/tutorialv2/includes/headline/title.part.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<a href="#edit-thumbnail" class="open-modal edit-thumbnail {{ class_modifier }}" title="{% trans "Modifier la miniature" %}">
<span class="visuallyhidden">{% trans "Modifier la miniature" %}</span>
</a>
{% crispy form_edit_thumbnail %}
{% endif %}
</div>
{% endif %}
Expand Down
31 changes: 0 additions & 31 deletions zds/tutorialv2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,29 +108,13 @@ def __init__(self, *args, **kwargs):


class ContentForm(ContainerForm):
description = forms.CharField(
label=_("Description"),
max_length=PublishableContent._meta.get_field("description").max_length,
required=False,
)

image = forms.FileField(
label=_("Sélectionnez le logo du contenu (max. {} Ko).").format(
str(settings.ZDS_APP["gallery"]["image_max_size"] / 1024)
),
validators=[with_svg_validator],
required=False,
)

type = forms.ChoiceField(choices=TYPE_CHOICES, required=False)

def _create_layout(self):
self.helper.layout = Layout(
IncludeEasyMDE(),
Field("title"),
Field("description"),
Field("type"),
Field("image"),
Field("introduction", css_class="md-editor preview-source"),
ButtonHolder(
StrictButton(_("Aperçu"), type="preview", name="preview", css_class="btn btn-grey preview-btn"),
Expand Down Expand Up @@ -163,19 +147,6 @@ def __init__(self, *args, **kwargs):
if "type" in self.initial:
self.helper["type"].wrap(Field, disabled=True)

def clean(self):
cleaned_data = super().clean()
image = cleaned_data.get("image", None)
if image is not None and image.size > settings.ZDS_APP["gallery"]["image_max_size"]:
self._errors["image"] = self.error_class(
[
_("Votre logo est trop lourd, la limite autorisée est de {} Ko").format(
settings.ZDS_APP["gallery"]["image_max_size"] / 1024
)
]
)
return cleaned_data


class EditContentForm(ContentForm):
title = None
Expand All @@ -185,7 +156,6 @@ class EditContentForm(ContentForm):
def _create_layout(self):
self.helper.layout = Layout(
IncludeEasyMDE(),
Field("image"),
Field("introduction", css_class="md-editor preview-source"),
StrictButton(_("Aperçu"), type="preview", name="preview", css_class="btn btn-grey preview-btn"),
HTML(
Expand All @@ -199,7 +169,6 @@ def _create_layout(self):
with text=form.conclusion.value %}{% endif %}'
),
Field("last_hash"),
Field("subcategory", template="crispy/checkboxselectmultiple.html"),
Field("msg_commit"),
ButtonHolder(StrictButton("Valider", type="submit")),
)
Expand Down
7 changes: 2 additions & 5 deletions zds/tutorialv2/urls/urls_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
DeleteContent,
EditTitle,
EditSubtitle,
EditThumbnailView,
)
from zds.tutorialv2.views.display.container import ContainerValidationView
from zds.tutorialv2.views.display.content import ContentValidationView
Expand Down Expand Up @@ -215,16 +216,12 @@ def get_version_pages():
path("enlever-contributeur/<int:pk>/", RemoveContributorFromContent.as_view(), name="remove-contributor"),
path("ajouter-auteur/<int:pk>/", AddAuthorToContent.as_view(), name="add-author"),
path("enlever-auteur/<int:pk>/", RemoveAuthorFromContent.as_view(), name="remove-author"),
# Modify the title and subtitle
path("modifier-titre/<int:pk>/", EditTitle.as_view(), name="edit-title"),
path("modifier-sous-titre/<int:pk>/", EditSubtitle.as_view(), name="edit-subtitle"),
# Modify the license
path("modifier-miniature/<int:pk>/", EditThumbnailView.as_view(), name="edit-thumbnail"),
path("modifier-licence/<int:pk>/", EditContentLicense.as_view(), name="edit-license"),
# Modify the tags
path("modifier-tags/<int:pk>/", EditTags.as_view(), name="edit-tags"),
# Modify the canonical link
path("modifier-lien-canonique/<int:pk>", EditCanonicalLinkView.as_view(), name="edit-canonical-link"),
# Modify the categories
path("modifier-categories/<int:pk>/", EditCategoriesView.as_view(), name="edit-categories"),
# beta:
path("activer-beta/<int:pk>/<slug:slug>/", ManageBetaContent.as_view(action="set"), name="set-beta"),
Expand Down
150 changes: 97 additions & 53 deletions zds/tutorialv2/views/contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import transaction
from django.forms import forms, CharField
from django.forms import forms, CharField, FileField
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.urls import reverse
Expand Down Expand Up @@ -37,6 +37,7 @@
from zds.mp.utils import send_mp, send_message_mp
from zds.utils.uuslug_wrapper import slugify
from zds.tutorialv2.models import CONTENT_TYPE_LIST
from zds.utils.validators import with_svg_validator

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -69,43 +70,26 @@ def get_context_data(self, **kwargs):
return context

def form_valid(self, form):
# create the object:
self.content = PublishableContent()
self.content.title = form.cleaned_data["title"]
self.content.description = form.cleaned_data["description"]
self.content.type = form.cleaned_data["type"]
self.content.licence = self.request.user.profile.licence # Use the preferred license of the user if it exists
self.content.creation_date = datetime.now()

gallery = Gallery.objects.create(
self.content = PublishableContent(
title=form.cleaned_data["title"],
type=form.cleaned_data["type"],
licence=self.request.user.profile.licence, # Use the preferred license of the user if it exists
creation_date=datetime.now(),
)

self.content.gallery = Gallery.objects.create(
title=self.content.title,
slug=slugify(self.content.title),
pubdate=datetime.now(),
)

# create image:
if "image" in self.request.FILES:
mixin = ImageCreateMixin()
mixin.gallery = gallery
try:
img = mixin.perform_create(str(_("Icône du contenu")), self.request.FILES["image"])
except NotAnImage:
form.add_error("image", _("Image invalide"))
return super().form_invalid(form)
img.pubdate = datetime.now()
self.content.gallery = gallery
self.content.save()
if "image" in self.request.FILES:
self.content.image = img
self.content.save()

# We need to save the content before changing its author list since it's a many-to-many relationship
self.content.authors.add(self.request.user)
self.content.save() # Commit to database before updating relationships

# Update relationships
self.content.authors.add(self.request.user)
self.content.ensure_author_gallery()
self.content.save()

# create a new repo :
# Create a new git repository
init_new_repo(
self.content,
form.cleaned_data["introduction"],
Expand Down Expand Up @@ -160,26 +144,6 @@ def form_valid(self, form):

publishable.update_date = datetime.now()

# update image
if "image" in self.request.FILES:
gallery_defaults = {
"title": publishable.title,
"slug": slugify(publishable.title),
"pubdate": datetime.now(),
}
gallery, _created = Gallery.objects.get_or_create(pk=publishable.gallery.pk, defaults=gallery_defaults)
mixin = ImageCreateMixin()
mixin.gallery = gallery
try:
img = mixin.perform_create(str(_("Icône du contenu")), self.request.FILES["image"])
except NotAnImage:
form.add_error("image", _("Image invalide"))
return super().form_invalid(form)
img.pubdate = datetime.now()
publishable.image = img

publishable.save()

# now, update the versioned information
sha = versioned.repo_update_top_container(
publishable.title,
Expand All @@ -188,10 +152,7 @@ def form_valid(self, form):
form.cleaned_data["conclusion"],
form.cleaned_data["msg_commit"],
)

# update relationships :
publishable.sha_draft = sha

publishable.save()

self.success_url = reverse("content:view", args=[publishable.pk, publishable.slug])
Expand Down Expand Up @@ -354,6 +315,89 @@ def update_sha_draft(publishable_content, sha):
publishable_content.save()


class EditThumbnailForm(forms.Form):
image = FileField(
label=_("Sélectionnez la miniature de la publication (max. {} ko).").format(
str(settings.ZDS_APP["gallery"]["image_max_size"] // 1024)
),
validators=[with_svg_validator],
required=True,
)

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

self.helper = FormHelper()
self.helper.form_method = "post"
self.helper.form_action = reverse("content:edit-thumbnail", kwargs={"pk": versioned_content.pk})
self.helper.form_id = "edit-thumbnail"
self.helper.form_class = "modal modal-flex"

self.helper.layout = Layout(
Field("image"),
StrictButton("Valider", type="submit"),
)

self.previous_page_url = reverse(
"content:view", kwargs={"pk": versioned_content.pk, "slug": versioned_content.slug}
)

def clean(self):
cleaned_data = super().clean()
image = cleaned_data.get("image", None)
if image is not None and image.size > settings.ZDS_APP["gallery"]["image_max_size"]:
self._errors["image"] = self.error_class(
[
_("Votre logo est trop lourd, la limite autorisée est de {} Ko").format(
settings.ZDS_APP["gallery"]["image_max_size"] / 1024
)
]
)
return cleaned_data


class EditThumbnailView(LoginRequiredMixin, SingleContentFormViewMixin):
modal_form = True
model = PublishableContent
form_class = EditThumbnailForm
success_message = _("La miniature a bien été changée.")

def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs["versioned_content"] = self.versioned_object
return kwargs

def form_valid(self, form):
publishable = self.object

# Get or create gallery
gallery_defaults = {
"title": publishable.title,
"slug": slugify(publishable.title),
"pubdate": datetime.now(),
}
gallery, _created = Gallery.objects.get_or_create(pk=publishable.gallery.pk, defaults=gallery_defaults)
publishable.gallery = gallery

# Create image
mixin = ImageCreateMixin()
mixin.gallery = gallery
try:
thumbnail = mixin.perform_create(str(_("Icône du contenu")), self.request.FILES["image"])
except NotAnImage:
form.add_error("image", _("Image invalide"))
return super().form_invalid(form)
thumbnail.pubdate = datetime.now()

# Update thumbnail
publishable.image = thumbnail
publishable.save()

messages.success(self.request, self.success_message)

return redirect(form.previous_page_url)


class DeleteContent(LoginRequiredMixin, SingleContentViewMixin, DeleteView):
model = PublishableContent
http_method_names = ["post"]
Expand Down
3 changes: 2 additions & 1 deletion zds/tutorialv2/views/display/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
ContentReaction,
)
from zds.tutorialv2.utils import last_participation_is_old, mark_read
from zds.tutorialv2.views.contents import EditTitleForm, EditSubtitleForm
from zds.tutorialv2.views.contents import EditTitleForm, EditSubtitleForm, EditThumbnailForm
from zds.tutorialv2.views.display.config import (
ConfigForContentDraftView,
ConfigForVersionView,
Expand Down Expand Up @@ -141,6 +141,7 @@ def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form_edit_title"] = EditTitleForm(self.versioned_object)
context["form_edit_subtitle"] = EditSubtitleForm(self.versioned_object)
context["form_edit_thumbnail"] = EditThumbnailForm(self.versioned_object)
context["display_config"] = ConfigForContentDraftView(self.request.user, self.object, self.versioned_object)
return context

Expand Down

0 comments on commit af7998a

Please sign in to comment.