Skip to content

Commit

Permalink
Merge 4658701 into b444923
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud-D committed May 13, 2020
2 parents b444923 + 4658701 commit a2ba197
Show file tree
Hide file tree
Showing 11 changed files with 419 additions and 72 deletions.
1 change: 1 addition & 0 deletions assets/scss/base/_forms.scss
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@
.checkbox,
.radio {
padding: 10px 0;
height: 100%;

input {
margin-top: 8px;
Expand Down
6 changes: 6 additions & 0 deletions templates/tutorialv2/view/content.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@
{% if content.licence %}
<p class="license">
{{ content.licence }}
<a href="#edit-license" class="open-modal">{% trans "Modifier la licence" %}</a>
</p>
{% else %}
<p class="license">
<a href="#edit-license" class="open-modal">Choisissez la licence de votre publication !</a>
</p>
{% endif %}
{% crispy form_edit_license %}

<h1 {% if content.image %}class="illu"{% endif %}>
{% if content.image %}
Expand Down
12 changes: 7 additions & 5 deletions zds/tutorialv2/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ class Meta:
pubdate = datetime.now()

@classmethod
def _prepare(cls, create, *, light=True, author_list=None, licence: Licence = None, add_category=True, **kwargs):
def _prepare(cls, create, *, light=True, author_list=None, licence: Licence = None,
add_license=True, add_category=True, **kwargs):
auths = author_list or []
given_licence = licence or Licence.objects.first()
if isinstance(given_licence, str) and given_licence:
given_licence = Licence.objects.filter(title=given_licence).first() or Licence.objects.first()
licence = given_licence or LicenceFactory()
if add_license:
given_licence = licence or Licence.objects.first()
if isinstance(given_licence, str) and given_licence:
given_licence = Licence.objects.filter(title=given_licence).first() or Licence.objects.first()
licence = given_licence or LicenceFactory()

text = text_content
if not light:
Expand Down
128 changes: 93 additions & 35 deletions zds/tutorialv2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,20 +281,6 @@ class ContentForm(ContainerForm):
widget=forms.CheckboxSelectMultiple()
)

licence = forms.ModelChoiceField(
label=(
_('Licence de votre publication (<a href="{0}" alt="{1}">En savoir plus sur les licences et {2}</a>).')
.format(
settings.ZDS_APP['site']['licenses']['licence_info_title'],
settings.ZDS_APP['site']['licenses']['licence_info_link'],
settings.ZDS_APP['site']['literal_name'],
)
),
queryset=Licence.objects.order_by('title').all(),
required=False,
empty_label=_('Choisir une licence')
)

helps = forms.ModelMultipleChoiceField(
label=_("Pour m'aider, je cherche un..."),
queryset=HelpWriting.objects.all(),
Expand Down Expand Up @@ -328,7 +314,6 @@ def _create_layout(self, hide_help):
HTML('{% if form.conclusion.value %}{% include "misc/preview.part.html" \
with text=form.conclusion.value %}{% endif %}'),
Field('last_hash'),
Field('licence'),
Field('subcategory', template='crispy/checkboxselectmultiple.html'),
)

Expand Down Expand Up @@ -367,6 +352,55 @@ def clean(self):
return cleaned_data


class EditContentLicenseForm(forms.Form):
license = forms.ModelChoiceField(
label=_('Licence de votre publication : '),
queryset=Licence.objects.order_by('title').all(),
required=True,
empty_label=_('Choisir une licence'),
error_messages={'required': _('Merci de choisir une licence.'),
'invalid_choice': _('Merci de choisir une licence valide dans la liste.')}
)

update_preferred_license = forms.BooleanField(
label=_('Je souhaite utiliser cette licence comme choix par défaut pour mes futures publications.'),
required=False
)

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

self.helper = FormHelper()
self.helper.form_class = 'content-wrapper'
self.helper.form_method = 'post'
self.helper.form_id = 'edit-license'
self.helper.form_class = 'modal modal-flex'
self.helper.form_action = reverse('content:edit-license', kwargs={'pk': content.pk})
self.previous_page_url = reverse('content:view',
kwargs={'pk': content.pk, 'slug': content.slug})
self._create_layout()

if 'type' in self.initial:
self.helper['type'].wrap(
Field,
disabled=True)

def _create_layout(self):
self.helper.layout = Layout(
HTML("""<p>{0} encourage l'utilisation de licences facilitant le partage,
telles que les licences <a href="https://creativecommons.org/">Creative Commons</a>.</p>
<p>Pour choisir la licence de votre publication, aidez-vous de la
<a href="{1}" alt="{2}">présentation
des différentes licences proposées sur le site</a>.</p>"""
.format(settings.ZDS_APP['site']['literal_name'],
settings.ZDS_APP['site']['licenses']['licence_info_title'],
settings.ZDS_APP['site']['licenses']['licence_info_link'])),
Field('license'),
Field('update_preferred_license'),
ButtonHolder(StrictButton('Valider', type='submit'))
)


class ExtractForm(FormWithTitle):

text = forms.CharField(
Expand Down Expand Up @@ -698,12 +732,20 @@ def __init__(self, content, *args, **kwargs):
self.helper.form_id = 'ask-validation'

self.no_subcategories = content.subcategory.count() == 0
no_category_msg = HTML(_("""<p><strong>Votre contenu n'est dans aucune catégorie.
Vous devez choisir une catégorie avant de demander la validation !</strong></p>
"""))
no_category_msg = HTML(_("""<p><strong>Votre publication n'est dans aucune catégorie.
Vous devez <a href="{}#{}">choisir une catégorie</a>
avant de demander la validation.</strong></p>"""
.format(reverse('content:edit', kwargs={'pk': content.pk, 'slug': content.slug}),
'div_id_subcategory')))

self.no_license = not content.licence
no_license_msg = HTML(_("""<p><strong>Vous n'avez pas choisi de licence pour votre publication.
Vous devez <a href="#edit-license" class="open-modal">choisir une licence</a>
avant de demander la validation.</strong></p>"""))

self.helper.layout = Layout(
no_category_msg if self.no_subcategories else None,
HTML(_('<p>Pensez à vérifier la licence de votre contenu avant de demander la validation.</p>')),
no_license_msg if self.no_license else None,
Field('text'),
Field('source'),
Field('version'),
Expand All @@ -717,21 +759,23 @@ def clean(self):

text = cleaned_data.get('text')

base_error_msg = "La validation n'a pas été demandée. "

if text is None or not text.strip():
self._errors['text'] = self.error_class(
[_('Vous devez fournir un commentaire aux validateurs.')])
if 'text' in cleaned_data:
del cleaned_data['text']
error = [_(base_error_msg + 'Vous devez fournir un commentaire aux validateurs.')]
self.add_error(field='text', error=error)

elif len(text) < 3:
self._errors['text'] = self.error_class(
[_('Votre commentaire doit faire au moins 3 caractères.')])
if 'text' in cleaned_data:
del cleaned_data['text']
error = _(base_error_msg + 'Votre commentaire doit faire au moins 3 caractères.')
self.add_error(field='text', error=error)

if self.no_subcategories:
self._errors['no_subcategories'] = self.error_class(
[_('Vous devez spécifier une catégorie pour votre publication.')])
error = [_(base_error_msg + 'Vous devez choisir au moins une catégorie pour votre publication.')]
self.add_error(field=None, error=error)

if self.no_license:
error = [_(base_error_msg + 'Vous devez choisir une licence pour votre publication.')]
self.add_error(field=None, error=error)

return cleaned_data

Expand Down Expand Up @@ -1169,13 +1213,21 @@ def __init__(self, content, *args, **kwargs):
self.helper.form_id = 'valid-publication'

self.no_subcategories = content.subcategory.count() == 0
no_category_msg = HTML(_("""<p><strong>Votre billet n'est dans aucune catégorie.
Vous devez choisir une catégorie avant de le publier !</strong></p>
"""))
no_category_msg = HTML(_("""<p><strong>Votre publication n'est dans aucune catégorie.
Vous devez <a href="{}#{}">choisir une catégorie</a>
avant de demander la validation.</strong></p>"""
.format(reverse('content:edit', kwargs={'pk': content.pk, 'slug': content.slug}),
'div_id_subcategory')))

self.no_license = not content.licence
no_license_msg = HTML(_("""<p><strong>Vous n'avez pas choisi de licence pour votre publication.
Vous devez <a href="{}">choisir une licence</a>
avant de demander la validation.</strong></p>"""
.format('#edit-license')))

self.helper.layout = Layout(
no_category_msg if self.no_subcategories else None,
HTML(_('<p>Pensez à vérifier la licence de votre billet avant de le publier.</p>')),
no_license_msg if self.no_license else None,
Field('source'),
HTML(_("<p>Ce billet sera publié directement et n'engage que vous.</p>")),
StrictButton(_('Publier'), type='submit')
Expand All @@ -1184,9 +1236,15 @@ def __init__(self, content, *args, **kwargs):
def clean(self):
cleaned_data = super(PublicationForm, self).clean()

base_error_msg = "La publication n'a pas été effectuée. "

if self.no_subcategories:
self._errors['no_subcategories'] = self.error_class(
[_('Vous devez spécifier une catégorie pour votre publication.')])
error = _(base_error_msg + 'Vous devez choisir au moins une catégorie pour votre publication.')
self.add_error(field=None, error=error)

if self.no_license:
error = _(base_error_msg + 'Vous devez choisir une licence pour votre publication.')
self.add_error(field=None, error=error)

return cleaned_data

Expand Down
4 changes: 3 additions & 1 deletion zds/tutorialv2/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,9 @@ def form_invalid(self, form):
else:
errors = form.errors.as_data()
if len(errors) > 0:
messages.error(self.request, list(errors.values())[0][0]) # only the first error is provided
# only the first error is provided
error_message = list(errors.values())[0][0].messages[0]
messages.error(self.request, error_message)
else:
messages.error(
self.request, _('Une erreur inconnue est survenue durant le traitement des données.'))
Expand Down
4 changes: 1 addition & 3 deletions zds/tutorialv2/tests/tests_front.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from selenium.webdriver.firefox.webdriver import WebDriver
from django.test import tag
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains

Expand Down Expand Up @@ -159,8 +159,6 @@ def test_the_editor_forgets_its_content_on_form_submission(self):
WebDriverWait(self.selenium, 10).until(ec.element_to_be_clickable(
(By.CSS_SELECTOR, 'input[type=checkbox][name=subcategory]')
)).click()
license_select = Select(find_element('#id_licence'))
license_select.select_by_index(len(license_select.options) - 1)

find_element('#id_title').send_keys('Oulipo')

Expand Down
9 changes: 2 additions & 7 deletions zds/tutorialv2/tests/tests_views/tests_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,6 @@ def test_basic_tutorial_workflow(self):
result_string = ''.join(a.decode() for a in result.streaming_content)
self.assertIn('<strong>markdown</strong>', result_string, 'We need the text to be properly formatted')

# edit tutorial:
new_licence = LicenceFactory()

result = self.client.post(
reverse('content:edit', args=[pk, slug]),
{
Expand All @@ -317,7 +314,6 @@ def test_basic_tutorial_workflow(self):
'introduction': random,
'conclusion': random,
'type': 'TUTORIAL',
'licence': new_licence.pk,
'subcategory': self.subcategory.pk,
'last_hash': versioned.compute_hash(),
'image': (settings.BASE_DIR / 'fixtures' / 'logo.png').open('rb')
Expand All @@ -330,12 +326,12 @@ def test_basic_tutorial_workflow(self):
tuto = PublishableContent.objects.get(pk=pk)
self.assertEqual(tuto.title, random)
self.assertEqual(tuto.description, random)
self.assertEqual(tuto.licence.pk, new_licence.pk)
self.assertEqual(tuto.licence, None)
versioned = tuto.load_version()
self.assertEqual(versioned.get_introduction(), random)
self.assertEqual(versioned.get_conclusion(), random)
self.assertEqual(versioned.description, random)
self.assertEqual(versioned.licence.pk, new_licence.pk)
self.assertEqual(versioned.licence, None)
self.assertNotEqual(versioned.slug, slug)

slug = tuto.slug # make the title change also change the slug !!
Expand Down Expand Up @@ -1517,7 +1513,6 @@ def test_import_create_content(self):
'introduction': some_text,
'conclusion': some_text,
'type': 'TUTORIAL',
'licence': self.licence.pk,
'subcategory': self.subcategory.pk,
},
follow=False)
Expand Down

0 comments on commit a2ba197

Please sign in to comment.