Hook form to db

This commit is contained in:
zandercymatics 2024-05-10 09:54:38 -06:00
parent dd9df90fb4
commit a55f339168
No known key found for this signature in database
GPG key ID: FF4636ABEC9682B7
4 changed files with 44 additions and 44 deletions

View file

@ -6,9 +6,24 @@ from django.core.validators import MaxLengthValidator
class ContactForm(forms.Form):
"""Form for adding or editing a contact"""
def __init__(self, *args, **kwargs):
kwargs.setdefault("label_suffix", "")
super(ContactForm, self).__init__(*args, **kwargs)
def to_database(self, obj):
"""
Adds this form's cleaned data to `obj` and saves `obj`.
Does nothing if form is not valid.
"""
if not self.is_valid():
return
for name, value in self.cleaned_data.items():
setattr(obj, name, value)
obj.save()
@classmethod
def from_database(cls, obj):
"""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
first_name = forms.CharField(
label="First name / given name",

View file

@ -23,7 +23,7 @@ class CheckUserProfileMiddleware:
# Check if setup is not finished
finished_setup = hasattr(request.user, "finished_setup") and request.user.finished_setup
if request.user.is_authenticated and not finished_setup:
setup_page = reverse("finish-contact-profile-setup", kwargs={'pk': request.user.pk})
setup_page = reverse("finish-contact-profile-setup", kwargs={'pk': request.user.contact.pk})
logout_page = reverse("logout")
excluded_pages = [
setup_page,

View file

@ -42,7 +42,7 @@
Your contact information
</legend>
{{form.first_name}}
{% comment %}
{% input_with_errors form.first_name %}
{% input_with_errors form.middle_name %}
@ -56,7 +56,7 @@
{% with add_class="usa-input--medium" %}
{% input_with_errors form.phone %}
{% endwith %}
{% endcomment %}
</fieldset>
<div>

View file

@ -1,10 +1,13 @@
from django.urls import reverse
from registrar.forms.contact import ContactForm
from registrar.models.contact import Contact
from registrar.views.utility.permission_views import ContactPermissionView
from django.views.generic.edit import FormMixin
# TODO we can and probably should generalize this at this rate.
class BaseContactView(ContactPermissionView):
def get(self, request, *args, **kwargs):
self._set_contact(request)
context = self.get_context_data(object=self.object)
@ -38,6 +41,7 @@ class BaseContactView(ContactPermissionView):
class ContactFormBaseView(BaseContactView, FormMixin):
def post(self, request, *args, **kwargs):
"""Form submission posts to this view.
@ -54,13 +58,6 @@ class ContactFormBaseView(BaseContactView, FormMixin):
def check_form(self, form):
return self.form_valid(form) if form.is_valid() else self.form_invalid(form)
def form_valid(self, form):
# updates session cache with contact
self._update_session_with_contact()
# superclass has the redirect
return super().form_valid(form)
def form_invalid(self, form):
# updates session cache with contact
self._update_session_with_contact()
@ -69,45 +66,33 @@ class ContactFormBaseView(BaseContactView, FormMixin):
return super().form_invalid(form)
class ContactProfileSetupView(ContactPermissionView):
class ContactProfileSetupView(ContactFormBaseView):
"""This view forces the user into providing additional details that
we may have missed from Login.gov"""
template_name = "finish_contact_setup.html"
form_class = ContactForm
model = Contact
def get_form_kwargs(self, *args, **kwargs):
"""Add domain_info.organization_name instance to make a bound form."""
form_kwargs = super().get_form_kwargs(*args, **kwargs)
form_kwargs["instance"] = self.object
return form_kwargs
def get_success_url(self):
"""Redirect to the nameservers page for the domain."""
# TODO - some logic should exist that navigates them to the domain request page if
# they clicked it on get.gov
def get(self, request, *args, **kwargs):
self._get_contact(request)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
# The user has finished their setup
def _get_contact(self, request):
"""
get domain from session cache or from db and set
to self.object
set session to self for downstream functions to
update session cache
"""
self.session = request.session
contact_pk = "contact:" + str(self.kwargs.get("pk"))
cached_contact = self.session.get(contact_pk)
# Add a notification that the update was successful
return reverse("home")
if cached_contact:
self.object = cached_contact
else:
self.object = self.get_object()
self._set_session_contact_pk()
def form_valid(self, form):
self.request.user.finished_setup = True
self.request.user.save()
def _set_session_contact_pk(self):
"""
Set contact pk in the session cache
"""
domain_pk = "contact:" + str(self.kwargs.get("pk"))
self.session[domain_pk] = self.object
form.to_database(self.object)
self._update_session_with_contact()
return super().form_valid(form)
def get_initial(self):
"""The initial value for the form (which is a formset here)."""
return self.form_class.from_database(self.object)