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): class ContactForm(forms.Form):
"""Form for adding or editing a contact""" """Form for adding or editing a contact"""
def __init__(self, *args, **kwargs): def to_database(self, obj):
kwargs.setdefault("label_suffix", "") """
super(ContactForm, self).__init__(*args, **kwargs) 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( first_name = forms.CharField(
label="First name / given name", label="First name / given name",

View file

@ -23,7 +23,7 @@ class CheckUserProfileMiddleware:
# Check if setup is not finished # Check if setup is not finished
finished_setup = hasattr(request.user, "finished_setup") and request.user.finished_setup finished_setup = hasattr(request.user, "finished_setup") and request.user.finished_setup
if request.user.is_authenticated and not 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") logout_page = reverse("logout")
excluded_pages = [ excluded_pages = [
setup_page, setup_page,

View file

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

View file

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