diff --git a/.github/workflows/loaddata.yaml b/.github/workflows/loaddata.yaml index e104a9f49..e611e9964 100644 --- a/.github/workflows/loaddata.yaml +++ b/.github/workflows/loaddata.yaml @@ -28,7 +28,7 @@ jobs: cf_password: ${{ secrets.CF_STAGING_PASSWORD }} cf_org: cisa-getgov-prototyping cf_space: staging - full_command: "cf run-task getgov-staging --wait --command 'python manage.py flush' --name flush" + full_command: "cf run-task getgov-staging --wait --command 'python manage.py flush --no-input' --name flush" - name: Load fake data for staging uses: 18f/cg-deploy-action@main diff --git a/docs/architecture/decisions/0016-django-form-wizard.md b/docs/architecture/decisions/0016-django-form-wizard.md new file mode 100644 index 000000000..8e785a196 --- /dev/null +++ b/docs/architecture/decisions/0016-django-form-wizard.md @@ -0,0 +1,29 @@ +# 16. Django Form Wizard + +Date: 2022-01-03 + +## Status + +Accepted + +## Context + +The application form by which registrants apply for a .gov domain is presented over many pages. + +Because we use server-side rendering, each page of the application is a unique HTML page with form fields surrounded by a form tag. + +Needing a way to coordinate state between the pages as a user fills in their application, we initially used the Form wizard from [django-formtools](https://django-formtools.readthedocs.io/en/latest/wizard.html). This eventually proved unworkable due to the lack of native ability to have more than one Django form object displayed on a single HTML page. + +However, a significant portion of the user workflow had already been coded, so it seemed prudent to port some of the formtools logic into our codebase. + +## Decision + +To maintain each page of the domain application as its own Django view class, inheriting common code from a parent class. + +To maintain Django form and formset class in accordance with the Django models whose data they collect, independently of the pages on which they appear. + +## Consequences + +The wizard implementation is now unique to our codebase, which will impact developer onboarding, in the form of additional time needed to understand how it works. + +A small amount of additional code to maintain is introduced. Impact is likely to be minor. Library functions which were not needed by our implementation were not ported. diff --git a/src/.flake8 b/src/.flake8 index 8c4d4851a..e1ca2cc9a 100644 --- a/src/.flake8 +++ b/src/.flake8 @@ -2,5 +2,6 @@ max-line-length = 88 max-complexity = 10 extend-ignore = E203 +per-file-ignores = __init__.py:F401,F403 # migrations are auto-generated and often break rules exclude=registrar/migrations/* diff --git a/src/Pipfile b/src/Pipfile index 7116e723a..4475c0886 100644 --- a/src/Pipfile +++ b/src/Pipfile @@ -17,7 +17,6 @@ oic = "*" pyjwkest = "*" psycopg2-binary = "*" whitenoise = "*" -django-formtools = "*" django-widget-tweaks = "*" cachetools = "*" requests = "*" diff --git a/src/Pipfile.lock b/src/Pipfile.lock index 17a6baee2..2a531a89b 100644 --- a/src/Pipfile.lock +++ b/src/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "c9762342448f1a70dbe93cc496e5fb868c67a73f3e51c4440e726f492f7dc5ee" + "sha256": "1668475ce39851bd84ff7be330afe9766f6823cf9095980ba3b220ced3a284f4" }, "pipfile-spec": 6, "requires": {}, @@ -120,7 +120,7 @@ "sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845", "sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f" ], - "markers": "python_version >= '3.6'", + "markers": "python_full_version >= '3.6.0'", "version": "==2.1.1" }, "cryptography": { @@ -184,11 +184,11 @@ }, "django-allow-cidr": { "hashes": [ - "sha256:2fd88ffe697caf0c1d0fd147b88cf44d81282c069bbc475166a2ff1637ad9155", - "sha256:d17347e75d6c02864022f52ed608775a5e9ab144d1a82bb40853714f125f5d87" + "sha256:24b71f70257e97bab9fdb5ad8342c96eeea1d45bc06a36332978574252219401", + "sha256:6709f4581dfd2a00476a134741a738a7f67714ec4f8596c55b22cf3b2ac5a12e" ], "index": "pypi", - "version": "==0.5.0" + "version": "==0.6.0" }, "django-auditlog": { "hashes": [ @@ -213,14 +213,6 @@ "index": "pypi", "version": "==3.7" }, - "django-formtools": { - "hashes": [ - "sha256:deb932be55b1d9419e37dc4d65dfbfeb8d307b71c8c11fd52f159aba5fc0deed", - "sha256:f5f32f62ec8192cd1bc55bd929ca7dff5a5f2addf9027db95a5906ecfaa64836" - ], - "index": "pypi", - "version": "==2.4" - }, "django-fsm": { "hashes": [ "sha256:e2c02cbf273fb9691aa9a907c29990afdd21a4adea09c5640344c93fbe03f8d9", @@ -229,17 +221,6 @@ "index": "pypi", "version": "==2.8.1" }, - "django-phonenumber-field": { - "extras": [ - "phonenumberslite" - ], - "hashes": [ - "sha256:969bbcab203d697ea44c38726bdc7d72ac9f1ba397694b9f57422b471ad73590", - "sha256:9e2b302f239e4703fa9030e44833db5eb524a731335fd77b0b703bd352fbe8d0" - ], - "index": "pypi", - "version": "==7.0.1" - }, "django-widget-tweaks": { "hashes": [ "sha256:9bfc5c705684754a83cc81da328b39ad1b80f32bd0f4340e2a810cbab4b0c00e", @@ -278,7 +259,7 @@ "hashes": [ "sha256:b1bead90b70cf6ec3f0710ae53a525360fa360d306a86583adc6bf83a4db537d" ], - "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2'", + "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.18.2" }, "gunicorn": { @@ -382,13 +363,6 @@ "markers": "python_version >= '3.7'", "version": "==22.0" }, - "phonenumberslite": { - "hashes": [ - "sha256:2b7452fe69c907b7638ff4cf7f8a773a6dfce26bf32d67ebf4dc74d5e31abb79", - "sha256:b7f56b77711e6b99c7890f20f1aaa705d9fe2514215446b8426c8515c198775f" - ], - "version": "==8.13.3" - }, "psycopg2-binary": { "hashes": [ "sha256:00475004e5ed3e3bf5e056d66e5dcdf41a0dc62efcd57997acd9135c40a08a50", @@ -517,7 +491,7 @@ "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86", "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'", + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==2.8.2" }, "python-dotenv": { @@ -549,7 +523,7 @@ "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'", + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.16.0" }, "sqlparse": { @@ -713,7 +687,7 @@ "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325", "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==0.7.0" }, "mypy": { @@ -796,7 +770,7 @@ "sha256:347187bdb476329d98f695c213d7295a846d1152ff4fe9bacb8a9590b8ee7053", "sha256:8a4eaf0d0495c7395bdab3589ac2db602797d76207242c17d470186815706610" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==2.10.0" }, "pyflakes": { @@ -804,7 +778,7 @@ "sha256:ec55bf7fe21fff7f1ad2f7da62363d749e2a470500eab1b555334b67aa1ef8cf", "sha256:ec8b276a6b60bd80defed25add7e439881c19e64850afd9b346283d4165fd0fd" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==3.0.1" }, "pyyaml": { @@ -850,7 +824,7 @@ "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174", "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==6.0" }, "six": { @@ -858,7 +832,7 @@ "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'", + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.16.0" }, "smmap": { @@ -866,7 +840,7 @@ "sha256:2aba19d6a040e78d8b09de5c57e96207b09ed71d8e55ce0959eeee6c8e190d94", "sha256:c840e62059cd3be204b0c9c9f74be2c09d5648eddd4580d9314c3ecde0b30936" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==5.0.0" }, "soupsieve": { @@ -874,7 +848,7 @@ "sha256:3b2503d3c7084a42b1ebd08116e5f81aadfaea95863628c80a3b774a11b7c759", "sha256:fc53893b3da2c33de295667a0e19f078c14bf86544af307354de5fcf12a3f30d" ], - "markers": "python_full_version >= '3.6.0'", + "markers": "python_version >= '3.6'", "version": "==2.3.2.post1" }, "sqlparse": { @@ -898,7 +872,7 @@ "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc", "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f" ], - "markers": "python_version < '3.11'", + "markers": "python_full_version < '3.11.0a7'", "version": "==2.0.1" }, "types-cachetools": { @@ -951,7 +925,7 @@ "sha256:7500c9625927c8ec60f54377d590f67b30c8e70ef4b8894214ac6e4cad233d2a", "sha256:780a4082c5fbc0fde6a2fcfe5e26e6efc1e8f425730863c04085769781f51eba" ], - "markers": "python_version >= '3.7'", + "markers": "python_full_version >= '3.7.0'", "version": "==2.1.2" }, "webob": { @@ -959,7 +933,7 @@ "sha256:73aae30359291c14fa3b956f8b5ca31960e420c28c1bec002547fb04928cf89b", "sha256:b64ef5141be559cfade448f044fa45c2260351edcb6a8ef6b7e00c7dcef0c323" ], - "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'", + "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.8.7" }, "webtest": { @@ -967,7 +941,7 @@ "sha256:2a001a9efa40d2a7e5d9cd8d1527c75f41814eb6afce2c3d207402547b1e5ead", "sha256:54bd969725838d9861a9fa27f8d971f79d275d94ae255f5c501f53bb6d9929eb" ], - "markers": "python_full_version >= '3.6.0' and python_version < '4'", + "markers": "python_version >= '3.6' and python_version < '4'", "version": "==3.0.0" } } diff --git a/src/registrar/config/settings.py b/src/registrar/config/settings.py index 82755d6cf..49c5a25d5 100644 --- a/src/registrar/config/settings.py +++ b/src/registrar/config/settings.py @@ -371,11 +371,13 @@ LOGGING = { "django": { "handlers": ["console"], "level": "INFO", + "propagate": False, }, # Django's template processor "django.template": { "handlers": ["console"], "level": "INFO", + "propagate": False, }, # Django's runserver "django.server": { @@ -393,16 +395,19 @@ LOGGING = { "oic": { "handlers": ["console"], "level": "INFO", + "propagate": False, }, # Django wrapper for OpenID Connect "djangooidc": { "handlers": ["console"], "level": "INFO", + "propagate": False, }, # Our app! "registrar": { "handlers": ["console"], "level": "DEBUG", + "propagate": False, }, }, # root logger catches anything, unless diff --git a/src/registrar/config/urls.py b/src/registrar/config/urls.py index 3bebba5df..fe02d389f 100644 --- a/src/registrar/config/urls.py +++ b/src/registrar/config/urls.py @@ -9,30 +9,60 @@ from django.contrib import admin from django.urls import include, path from django.views.generic import RedirectView -from registrar.views import health, index, profile, whoami -from registrar.forms import ApplicationWizard, WIZARD_CONDITIONS +from registrar import views +from registrar.views.application import Step +from registrar.views.utility import always_404 from api.views import available -APPLICATION_URL_NAME = "application_step" -application_wizard = ApplicationWizard.as_view( - url_name=APPLICATION_URL_NAME, - done_step_name="finished", - condition_dict=WIZARD_CONDITIONS, -) +APPLICATION_NAMESPACE = views.ApplicationWizard.URL_NAMESPACE +application_urls = [ + path("", views.ApplicationWizard.as_view(), name=""), + path("finished/", views.Finished.as_view(), name="finished"), +] + +# dynamically generate the other application_urls +for step, view in [ + # add/remove steps here + (Step.ORGANIZATION_TYPE, views.OrganizationType), + (Step.ORGANIZATION_FEDERAL, views.OrganizationFederal), + (Step.ORGANIZATION_ELECTION, views.OrganizationElection), + (Step.ORGANIZATION_CONTACT, views.OrganizationContact), + (Step.AUTHORIZING_OFFICIAL, views.AuthorizingOfficial), + (Step.CURRENT_SITES, views.CurrentSites), + (Step.DOTGOV_DOMAIN, views.DotgovDomain), + (Step.PURPOSE, views.Purpose), + (Step.YOUR_CONTACT, views.YourContact), + (Step.OTHER_CONTACTS, views.OtherContacts), + (Step.SECURITY_EMAIL, views.SecurityEmail), + (Step.ANYTHING_ELSE, views.AnythingElse), + (Step.REQUIREMENTS, views.Requirements), + (Step.REVIEW, views.Review), +]: + application_urls.append(path(f"{step}/", view.as_view(), name=step)) + urlpatterns = [ - path("", index.index, name="home"), - path("whoami/", whoami.whoami, name="whoami"), + path("", views.index, name="home"), + path("whoami/", views.whoami, name="whoami"), path("admin/", admin.site.urls), - path("application//edit/", application_wizard, name="edit-application"), - path("health/", health.health), - path("edit_profile/", profile.edit_profile, name="edit-profile"), + path( + "application//edit/", + views.ApplicationWizard.as_view(), + name=views.ApplicationWizard.EDIT_URL_NAME, + ), + path("health/", views.health), + path("edit_profile/", views.edit_profile, name="edit-profile"), path("openid/", include("djangooidc.urls")), - path("register/", application_wizard, name="application"), - path("register//", application_wizard, name=APPLICATION_URL_NAME), + path("register/", include((application_urls, APPLICATION_NAMESPACE))), path("api/v1/available/", available, name="available"), + path( + "todo", + lambda r: always_404(r, "We forgot to include this link, sorry."), + name="todo", + ), ] + if not settings.DEBUG: urlpatterns += [ # redirect to login.gov diff --git a/src/registrar/forms/__init__.py b/src/registrar/forms/__init__.py index 806a2309c..954fff109 100644 --- a/src/registrar/forms/__init__.py +++ b/src/registrar/forms/__init__.py @@ -1,4 +1,2 @@ -from .edit_profile import EditProfileForm -from .application_wizard import ApplicationWizard, WIZARD_CONDITIONS - -__all__ = ["EditProfileForm", "ApplicationWizard", "WIZARD_CONDITIONS"] +from .edit_profile import * +from .application_wizard import * diff --git a/src/registrar/forms/application_wizard.py b/src/registrar/forms/application_wizard.py index 3dcb30df2..fc780b760 100644 --- a/src/registrar/forms/application_wizard.py +++ b/src/registrar/forms/application_wizard.py @@ -1,26 +1,14 @@ -"""Forms Wizard for creating a new domain application.""" - from __future__ import annotations # allows forward references in annotations - import logging -from typing import Union - from django import forms from django.core.validators import RegexValidator -from django.shortcuts import render -from django.contrib.auth.mixins import LoginRequiredMixin -from django.urls import resolve from django.utils.safestring import mark_safe -from formtools.wizard.views import NamedUrlSessionWizardView # type: ignore -from formtools.wizard.storage.session import SessionStorage # type: ignore - from phonenumber_field.formfields import PhoneNumberField # type: ignore from registrar.models import Contact, DomainApplication, Domain - logger = logging.getLogger(__name__) # nosec because this use of mark_safe does not introduce a cross-site scripting @@ -32,10 +20,19 @@ REQUIRED_SUFFIX = mark_safe( # nosec class RegistrarForm(forms.Form): - """Subclass used to remove the default colon suffix from all fields.""" + """ + A common set of methods and configuration. + + The registrar's domain application is several pages of "steps". + Each step is an HTML form containing one or more Django "forms". + + Subclass this class to create new forms. + """ def __init__(self, *args, **kwargs): kwargs.setdefault("label_suffix", "") + # save a reference to an application object + self.application = kwargs.pop("application", None) super(RegistrarForm, self).__init__(*args, **kwargs) def to_database(self, obj: DomainApplication | Contact): @@ -50,10 +47,14 @@ class RegistrarForm(forms.Form): setattr(obj, name, value) obj.save() - def from_database(self, obj: DomainApplication | Contact): - """Initializes this form's fields with values gotten from `obj`.""" - for name in self.declared_fields.keys(): - self.initial[name] = getattr(obj, name) # type: ignore + @classmethod + def from_database(cls, obj: DomainApplication | Contact | None): + """Returns a dict of form field values gotten from `obj`.""" + if obj is None: + return {} + return { + name: getattr(obj, name) for name in cls.declared_fields.keys() + } # type: ignore class OrganizationTypeForm(RegistrarForm): @@ -142,10 +143,11 @@ class OrganizationContactForm(RegistrarForm): def clean_federal_agency(self): """Require something to be selected when this is a federal agency.""" federal_agency = self.cleaned_data.get("federal_agency", None) - # need the wizard object to know if this is federal - context = self.get_context() - print(context) - if wizard._is_federal(): + # need the application object to know if this is federal + if self.application is None: + # hmm, no saved application object? + raise ValueError("Form has no active application object.") + if self.application.is_federal: if not federal_agency: # no answer was selected raise forms.ValidationError("Please select your federal agency.", code="required") @@ -154,7 +156,6 @@ class OrganizationContactForm(RegistrarForm): class AuthorizingOfficialForm(RegistrarForm): def to_database(self, obj): - """Adds this form's cleaned data to `obj` and saves `obj`.""" if not self.is_valid(): return contact = getattr(obj, "authorizing_official", None) @@ -166,11 +167,10 @@ class AuthorizingOfficialForm(RegistrarForm): obj.authorizing_official = contact obj.save() - def from_database(self, obj): - """Initializes this form's fields with values gotten from `obj`.""" + @classmethod + def from_database(cls, obj): contact = getattr(obj, "authorizing_official", None) - if contact is not None: - super().from_database(contact) + return super().from_database(contact) first_name = forms.CharField( label="First name/given name", @@ -201,7 +201,6 @@ class AuthorizingOfficialForm(RegistrarForm): class CurrentSitesForm(RegistrarForm): def to_database(self, obj): - """Adds this form's cleaned data to `obj` and saves `obj`.""" if not self.is_valid(): return obj.save() @@ -210,11 +209,13 @@ class CurrentSitesForm(RegistrarForm): # TODO: ability to update existing records obj.current_websites.create(website=normalized) - def from_database(self, obj): - """Initializes this form's fields with values gotten from `obj`.""" + @classmethod + def from_database(cls, obj): current_website = obj.current_websites.first() if current_website is not None: - self.initial["current_site"] = current_website.website + return {"current_site": current_website.website} + else: + return {} current_site = forms.CharField( required=False, @@ -246,7 +247,6 @@ class CurrentSitesForm(RegistrarForm): class DotGovDomainForm(RegistrarForm): def to_database(self, obj): - """Adds this form's cleaned data to `obj` and saves `obj`.""" if not self.is_valid(): return normalized = Domain.normalize( @@ -270,15 +270,18 @@ class DotGovDomainForm(RegistrarForm): # TODO: ability to update existing records obj.alternative_domains.create(website=normalized) - def from_database(self, obj): - """Initializes this form's fields with values gotten from `obj`.""" + @classmethod + def from_database(cls, obj): + values = {} requested_domain = getattr(obj, "requested_domain", None) if requested_domain is not None: - self.initial["requested_domain"] = requested_domain.sld + values["requested_domain"] = requested_domain.sld alternative_domain = obj.alternative_domains.first() if alternative_domain is not None: - self.initial["alternative_domain"] = alternative_domain.sld + values["alternative_domain"] = alternative_domain.sld + + return values requested_domain = forms.CharField( label="What .gov domain do you want?", @@ -329,7 +332,6 @@ class PurposeForm(RegistrarForm): class YourContactForm(RegistrarForm): def to_database(self, obj): - """Adds this form's cleaned data to `obj` and saves `obj`.""" if not self.is_valid(): return contact = getattr(obj, "submitter", None) @@ -341,11 +343,10 @@ class YourContactForm(RegistrarForm): obj.submitter = contact obj.save() - def from_database(self, obj): - """Initializes this form's fields with values gotten from `obj`.""" + @classmethod + def from_database(cls, obj): contact = getattr(obj, "submitter", None) - if contact is not None: - super().from_database(contact) + return super().from_database(contact) first_name = forms.CharField( label="First name/given name", @@ -376,7 +377,6 @@ class YourContactForm(RegistrarForm): class OtherContactsForm(RegistrarForm): def to_database(self, obj): - """Adds this form's cleaned data to `obj` and saves `obj`.""" if not self.is_valid(): return obj.save() @@ -390,11 +390,10 @@ class OtherContactsForm(RegistrarForm): super().to_database(contact) obj.other_contacts.add(contact) - def from_database(self, obj): - """Initializes this form's fields with values gotten from `obj`.""" + @classmethod + def from_database(cls, obj): other_contacts = obj.other_contacts.first() - if other_contacts is not None: - super().from_database(other_contacts) + return super().from_database(other_contacts) first_name = forms.CharField( label="First name/given name", @@ -447,266 +446,3 @@ class RequirementsForm(RegistrarForm): ), required=False, # use field validation to enforce this ) - - def clean_is_policy_acknowledged(self): - """This box must be checked to proceed but offer a clear error.""" - # already converted to a boolean - is_acknowledged = self.cleaned_data["is_policy_acknowledged"] - if not is_acknowledged: - raise forms.ValidationError( - "You must read and agree to the .gov domain requirements to proceed.", - code="invalid", - ) - return is_acknowledged - - -class ReviewForm(RegistrarForm): - """ - Empty class for the review page. - - It gets included as part of the form, but does not have any form fields itself. - """ - - def to_database(self, _): - """This form has no data. Do nothing.""" - pass - - pass - - -class Step: - """Names for each page of the application wizard.""" - - ORGANIZATION_TYPE = "organization_type" - ORGANIZATION_FEDERAL = "organization_federal" - ORGANIZATION_ELECTION = "organization_election" - ORGANIZATION_CONTACT = "organization_contact" - AUTHORIZING_OFFICIAL = "authorizing_official" - CURRENT_SITES = "current_sites" - DOTGOV_DOMAIN = "dotgov_domain" - PURPOSE = "purpose" - YOUR_CONTACT = "your_contact" - OTHER_CONTACTS = "other_contacts" - SECURITY_EMAIL = "security_email" - ANYTHING_ELSE = "anything_else" - REQUIREMENTS = "requirements" - REVIEW = "review" - - -# List of forms in our wizard. -# Each entry is a tuple of a name and a form subclass -FORMS = [ - (Step.ORGANIZATION_TYPE, OrganizationTypeForm), - (Step.ORGANIZATION_FEDERAL, OrganizationFederalForm), - (Step.ORGANIZATION_ELECTION, OrganizationElectionForm), - (Step.ORGANIZATION_CONTACT, OrganizationContactForm), - (Step.AUTHORIZING_OFFICIAL, AuthorizingOfficialForm), - (Step.CURRENT_SITES, CurrentSitesForm), - (Step.DOTGOV_DOMAIN, DotGovDomainForm), - (Step.PURPOSE, PurposeForm), - (Step.YOUR_CONTACT, YourContactForm), - (Step.OTHER_CONTACTS, OtherContactsForm), - (Step.SECURITY_EMAIL, SecurityEmailForm), - (Step.ANYTHING_ELSE, AnythingElseForm), - (Step.REQUIREMENTS, RequirementsForm), - (Step.REVIEW, ReviewForm), -] - -# Dict to match up the right template with the right step. -TEMPLATES = { - Step.ORGANIZATION_TYPE: "application_org_type.html", - Step.ORGANIZATION_FEDERAL: "application_org_federal.html", - Step.ORGANIZATION_ELECTION: "application_org_election.html", - Step.ORGANIZATION_CONTACT: "application_org_contact.html", - Step.AUTHORIZING_OFFICIAL: "application_authorizing_official.html", - Step.CURRENT_SITES: "application_current_sites.html", - Step.DOTGOV_DOMAIN: "application_dotgov_domain.html", - Step.PURPOSE: "application_purpose.html", - Step.YOUR_CONTACT: "application_your_contact.html", - Step.OTHER_CONTACTS: "application_other_contacts.html", - Step.SECURITY_EMAIL: "application_security_email.html", - Step.ANYTHING_ELSE: "application_anything_else.html", - Step.REQUIREMENTS: "application_requirements.html", - Step.REVIEW: "application_review.html", -} - -# We need to pass our page titles as context to the templates -TITLES = { - Step.ORGANIZATION_TYPE: "Type of organization", - Step.ORGANIZATION_FEDERAL: "Type of organization — Federal", - Step.ORGANIZATION_ELECTION: "Type of organization — Election board", - Step.ORGANIZATION_CONTACT: "Organization name and mailing address", - Step.AUTHORIZING_OFFICIAL: "Authorizing official", - Step.CURRENT_SITES: "Organization website", - Step.DOTGOV_DOMAIN: ".gov domain", - Step.PURPOSE: "Purpose of your domain", - Step.YOUR_CONTACT: "Your contact information", - Step.OTHER_CONTACTS: "Other contacts for your domain", - Step.SECURITY_EMAIL: "Security email for public use", - Step.ANYTHING_ELSE: "Anything else we should know?", - Step.REQUIREMENTS: "Requirements for registration and operation of .gov domains", - Step.REVIEW: "Review and submit your domain request", -} - - -# We can use a dictionary with step names and callables that return booleans -# to show or hide particular steps based on the state of the process. -WIZARD_CONDITIONS = { - "organization_federal": DomainApplication.show_organization_federal, - "organization_election": DomainApplication.show_organization_election, -} - - -class TrackingStorage(SessionStorage): - - """Storage subclass that keeps track of what the current_step has been.""" - - def _set_current_step(self, step): - super()._set_current_step(step) - - step_history = self.extra_data.setdefault("step_history", []) - # can't serialize a set, so keep list entries unique - if step not in step_history: - step_history.append(step) - - -class ApplicationWizard(LoginRequiredMixin, NamedUrlSessionWizardView): - - """Multi-page form ("wizard") for new domain applications. - - This sets up a sequence of forms that gather information for new - domain applications. Each form in the sequence has its own URL and - the progress through the form is stored in the Django session (thus - "NamedUrlSessionWizardView"). - - Caution: due to the redirect performed by using NamedUrlSessionWizardView, - many methods, such as `process_step`, are called TWICE per request. For - this reason, methods in this class need to be idempotent. - """ - - form_list = FORMS - storage_name = "registrar.forms.application_wizard.TrackingStorage" - - def get_template_names(self): - """Template for the current step. - - The return is a singleton list. - """ - return [TEMPLATES[self.steps.current]] - - def _is_federal(self) -> Union[bool, None]: - """Return whether this application is from a federal agency. - - Returns True if we know that this application is from a federal - agency, False if we know that it is not and None if there isn't an - answer yet for that question. - """ - return self.get_application_object().is_federal() - - def get_context_data(self, form, **kwargs): - """Add title information to the context for all steps.""" - context = super().get_context_data(form=form, **kwargs) - context["form_titles"] = TITLES - - # Add information about which steps should be unlocked - # TODO: sometimes the first step doesn't get added to the step history - # so add it here - context["visited"] = self.storage.extra_data.get("step_history", []) + [ - self.steps.first - ] - - if self.steps.current == Step.ORGANIZATION_CONTACT: - context["is_federal"] = self._is_federal() - if self.steps.current == Step.REVIEW: - context["step_cls"] = Step - application = self.get_application_object() - context["application"] = application - return context - - def get_application_object(self) -> DomainApplication: - """ - Attempt to match the current wizard with a DomainApplication. - - Will create an application if none exists. - """ - if "application_id" in self.storage.extra_data: - id = self.storage.extra_data["application_id"] - try: - return DomainApplication.objects.get( - creator=self.request.user, - pk=id, - ) - except DomainApplication.DoesNotExist: - logger.debug("Application id %s did not have a DomainApplication" % id) - - application = DomainApplication.objects.create(creator=self.request.user) - self.storage.extra_data["application_id"] = application.id - return application - - def form_to_database(self, form: RegistrarForm) -> DomainApplication: - """ - Unpack the form responses onto the model object properties. - - Saves the application to the database. - """ - application = self.get_application_object() - - if form is not None and hasattr(form, "to_database"): - form.to_database(application) - - return application - - def process_step(self, form): - """ - Hook called on every POST request, if the form is valid. - - Do not manipulate the form data here. - """ - # save progress - self.form_to_database(form=form) - return self.get_form_step_data(form) - - def get_form(self, step=None, data=None, files=None): - """This method constructs the form for a given step.""" - form = super().get_form(step, data, files) - - # restore from database, but only if a record has already - # been associated with this wizard instance - if "application_id" in self.storage.extra_data: - application = self.get_application_object() - form.from_database(application) - return form - - def post(self, *args, **kwargs): - """This method handles POST requests.""" - step = self.steps.current - # always call super() first, to do important pre-processing - rendered = super().post(*args, **kwargs) - # if user opted to save their progress, - # return them to the page they were already on - button = self.request.POST.get("submit_button", None) - if button == "save": - return self.render_goto_step(step) - # otherwise, proceed as normal - return rendered - - def get(self, *args, **kwargs): - """This method handles GET requests.""" - current_url = resolve(self.request.path_info).url_name - # always call super(), it handles important redirect logic - rendered = super().get(*args, **kwargs) - # if user visited via an "edit" url, associate the id of the - # application they are trying to edit to this wizard instance - if current_url == "edit-application" and "id" in kwargs: - self.storage.extra_data["application_id"] = kwargs["id"] - return rendered - - def done(self, form_list, form_dict, **kwargs): - """Called when the data for every form is submitted and validated.""" - application = self.get_application_object() - application.submit() # change the status to submitted - application.save() - logger.debug("Application object saved: %s", application.id) - return render( - self.request, "application_done.html", {"application_id": application.id} - ) diff --git a/src/registrar/models/domain_application.py b/src/registrar/models/domain_application.py index 4795d0195..ab59192ac 100644 --- a/src/registrar/models/domain_application.py +++ b/src/registrar/models/domain_application.py @@ -1,5 +1,5 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union +from typing import Union from django.apps import apps from django.db import models @@ -7,9 +7,6 @@ from django_fsm import FSMField, transition # type: ignore from .utility.time_stamped_model import TimeStampedModel -if TYPE_CHECKING: - from ..forms.application_wizard import ApplicationWizard - class DomainApplication(TimeStampedModel): @@ -460,30 +457,17 @@ class DomainApplication(TimeStampedModel): # during the application flow. They are policies about the application so # they appear here. - @staticmethod - def _get_organization_type(wizard: ApplicationWizard) -> Union[str, None]: - """Extract the answer to the organization type question from the wizard.""" - # using the step data from the storage is a workaround for this - # bug in django-formtools version 2.4 - # https://github.com/jazzband/django-formtools/issues/220 - type_data = wizard.storage.get_step_data("organization_type") - if type_data: - return type_data.get("organization_type-organization_type") - return None - - @staticmethod - def show_organization_federal(wizard: ApplicationWizard) -> bool: + def show_organization_federal(self) -> bool: """Show this step if the answer to the first question was "federal".""" - user_choice = DomainApplication._get_organization_type(wizard) + user_choice = self.organization_type return user_choice == DomainApplication.OrganizationChoices.FEDERAL - @staticmethod - def show_organization_election(wizard: ApplicationWizard) -> bool: + def show_organization_election(self) -> bool: """Show this step if the answer to the first question implies it. This shows for answers that aren't "Federal" or "Interstate". """ - user_choice = DomainApplication._get_organization_type(wizard) + user_choice = self.organization_type excluded = [ DomainApplication.OrganizationChoices.FEDERAL, DomainApplication.OrganizationChoices.INTERSTATE, diff --git a/src/registrar/templates/application_anything_else.html b/src/registrar/templates/application_anything_else.html index 153d547e2..1394ea093 100644 --- a/src/registrar/templates/application_anything_else.html +++ b/src/registrar/templates/application_anything_else.html @@ -6,14 +6,13 @@

Is there anything else we should know about your domain request?

-
+
- {{ wizard.management_form }} {% csrf_token %}
- {{ wizard.form.anything_else|add_label_class:"usa-label usa-sr-only" }} - {{ wizard.form.anything_else|add_class:"usa-textarea usa-character-count__field"|attr:"aria-describedby:instructions"|attr:"maxlength=500" }} + {{ forms.0.anything_else|add_label_class:"usa-label usa-sr-only" }} + {{ forms.0.anything_else|add_class:"usa-textarea usa-character-count__field"|attr:"aria-describedby:instructions"|attr:"maxlength=500" }} You can enter up to 500 characters
diff --git a/src/registrar/templates/application_authorizing_official.html b/src/registrar/templates/application_authorizing_official.html index 1265fd5ff..5fee4bc4b 100644 --- a/src/registrar/templates/application_authorizing_official.html +++ b/src/registrar/templates/application_authorizing_official.html @@ -9,7 +9,7 @@

Who is the authorizing official for your organization?

-

Your authorizing official is the person within your organization who can authorize your domain request. This is generally the highest ranking or highest elected official in your organization. Read more about who can serve as an authorizing official. +

Your authorizing official is the person within your organization who can authorize your domain request. This is generally the highest ranking or highest elected official in your organization. Read more about who can serve as an authorizing official.

@@ -21,8 +21,7 @@ {% include "includes/required_fields.html" %} - - {{ wizard.management_form }} + {% csrf_token %}
@@ -30,17 +29,17 @@ Who is the authorizing official for your organization? - {% input_with_errors wizard.form.first_name %} + {% input_with_errors forms.0.first_name %} - {% input_with_errors wizard.form.middle_name %} + {% input_with_errors forms.0.middle_name %} - {% input_with_errors wizard.form.last_name %} + {% input_with_errors forms.0.last_name %} - {% input_with_errors wizard.form.title %} + {% input_with_errors forms.0.title %} - {% input_with_errors wizard.form.email %} + {% input_with_errors forms.0.email %} - {% input_with_errors wizard.form.phone add_class="usa-input--medium" %} + {% input_with_errors forms.0.phone add_class="usa-input--medium" %}
diff --git a/src/registrar/templates/application_current_sites.html b/src/registrar/templates/application_current_sites.html index 9684a6113..5b3943ef7 100644 --- a/src/registrar/templates/application_current_sites.html +++ b/src/registrar/templates/application_current_sites.html @@ -5,11 +5,10 @@ {% block form_content %} - - {{ wizard.management_form }} + {% csrf_token %} - {% input_with_errors wizard.form.current_site %} + {% input_with_errors forms.0.form.current_site %} {{ block.super }} diff --git a/src/registrar/templates/application_done.html b/src/registrar/templates/application_done.html index 267a39ca6..70758baa6 100644 --- a/src/registrar/templates/application_done.html +++ b/src/registrar/templates/application_done.html @@ -19,7 +19,7 @@ your authorizing official, and any contacts you added.

meets our naming requirements. -
  • You can check the +
  • You can check the status of your request at any time.
  • @@ -32,9 +32,9 @@ your authorizing official, and any contacts you added.

    Before your domain can be used we'll need information about your domain name servers. If you have this information you can enter it now. If you don't have it, that's okay. You can enter it later on the -manage your domains page. +manage your domains page.

    -

    Enter DNS name servers

    +

    Enter DNS name servers

    {% endblock %} diff --git a/src/registrar/templates/application_dotgov_domain.html b/src/registrar/templates/application_dotgov_domain.html index 70582a8b7..dc968b278 100644 --- a/src/registrar/templates/application_dotgov_domain.html +++ b/src/registrar/templates/application_dotgov_domain.html @@ -3,7 +3,7 @@ {% load widget_tweaks static%} {% block form_content %} -

    Before requesting a .gov domain, please make sure it meets our naming requirements. Your domain name must: +

    Before requesting a .gov domain, please make sure it meets our naming requirements. Your domain name must:

    • Be available
    • Be unique
    • @@ -21,12 +21,11 @@ {% include "includes/domain_example__city.html" %}
    - +

    What .gov domain do you want?

    After you enter your domain, we’ll make sure it’s available and that it meets some of our naming requirements. If your domain passes these initial checks, we’ll verify that it meets all of our requirements once you complete and submit the rest of this form.

    This question is required.

    - {{ wizard.management_form }} {% csrf_token %} {% if wizard.form.requested_domain.errors %} diff --git a/src/registrar/templates/application_form.html b/src/registrar/templates/application_form.html index 580aa4d66..52052f536 100644 --- a/src/registrar/templates/application_form.html +++ b/src/registrar/templates/application_form.html @@ -1,7 +1,7 @@ {% extends 'base.html' %} -{% load static widget_tweaks %} +{% load static widget_tweaks namespaced_urls %} -{% block title %}Apply for a .gov domain – {{form_titles|get_item:wizard.steps.current}}{% endblock %} +{% block title %}Apply for a .gov domain – {{form_titles|get_item:steps.current}}{% endblock %} {% block content %}
    @@ -10,8 +10,8 @@
    - {% if wizard.steps.prev %} - + {% if steps.prev %} + Previous step @@ -37,12 +37,11 @@ {% endfor %} {% endif %} -

    {{form_titles|get_item:wizard.steps.current}}

    - +

    {{form_titles|get_item:steps.current}}

    {% block form_content %}
    - {% if wizard.steps.next %} + {% if steps.next %}