From 867e84ae91c071dd2a36d733000409cb108cb848 Mon Sep 17 00:00:00 2001 From: Glandos Date: Thu, 1 Jul 2021 22:59:25 +0200 Subject: [PATCH] add validator for default_currency This force the usage of project's id that must be provided to the form --- ihatemoney/api/common.py | 2 +- ihatemoney/forms.py | 22 ++++++++++++++++++++++ ihatemoney/web.py | 2 +- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ihatemoney/api/common.py b/ihatemoney/api/common.py index cd247cdf..ede76e46 100644 --- a/ihatemoney/api/common.py +++ b/ihatemoney/api/common.py @@ -69,7 +69,7 @@ class ProjectHandler(Resource): return "DELETED" def put(self, project): - form = EditProjectForm(meta={"csrf": False}) + form = EditProjectForm(id=project.id, meta={"csrf": False}) if form.validate() and current_app.config.get("ALLOW_PUBLIC_PROJECT_CREATION"): form.update(project) db.session.commit() diff --git a/ihatemoney/forms.py b/ihatemoney/forms.py index fcb9f9a4..2085ffe1 100644 --- a/ihatemoney/forms.py +++ b/ihatemoney/forms.py @@ -1,5 +1,6 @@ from datetime import datetime from re import match +from types import SimpleNamespace import email_validator from flask import request @@ -110,6 +111,10 @@ class EditProjectForm(FlaskForm): default_currency = SelectField(_("Default Currency"), validators=[DataRequired()]) def __init__(self, *args, **kwargs): + if not hasattr(self, "id"): + # We must access the project to validate the default currency. + # Mimics a StringField. Defaut to empty string to ensure that query run smoothly. + self.id = SimpleNamespace(data=kwargs.pop("id", "")) super().__init__(*args, **kwargs) self.default_currency.choices = [ (currency_name, render_localized_currency(currency_name, detailed=True)) @@ -142,6 +147,23 @@ class EditProjectForm(FlaskForm): ) return project + def validate_default_currency(form, field): + project = Project.query.get(form.id.data) + if ( + project is not None + and field.data == CurrencyConverter.no_currency + and project.has_multiple_currencies() + ): + raise ValidationError( + _( + ( + "This project already uses different currencies" + "and can't be set to 'No Currency'" + ) + ) + ) + pass + def update(self, project): """Update the project with the information from the form""" project.name = self.name.data diff --git a/ihatemoney/web.py b/ihatemoney/web.py index c0afab91..41940b30 100644 --- a/ihatemoney/web.py +++ b/ihatemoney/web.py @@ -399,7 +399,7 @@ def reset_password(): @main.route("//edit", methods=["GET", "POST"]) def edit_project(): - edit_form = EditProjectForm() + edit_form = EditProjectForm(id=g.project.id) import_form = UploadForm() # Import form if import_form.validate_on_submit():