Skip to content

Commit

Permalink
Redirect to current page on success
Browse files Browse the repository at this point in the history
  • Loading branch information
brylie committed Jan 7, 2024
1 parent 7e8bcfe commit e077192
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions homes/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from django.urls import reverse

from django.utils.translation import gettext as _
from django.views.generic.edit import FormView
Expand Down Expand Up @@ -173,7 +174,6 @@ def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
class HomeUserRelationListView(LoginRequiredMixin, FormView):
form_class = AddCaregiverForm # Use form_class instead of form
template_name = "homes/home_user_relation_list.html"
success_url = "/success-url/" # Modify with your success URL

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
Expand All @@ -198,7 +198,7 @@ def form_valid(self, form):
# TODO: Send an invitation email
error_message = _("User does not exist")
form.add_error("email", error_message)
messages.error(self.request, error_message)

return self.form_invalid(form)

user = user_model.objects.get(email=email)
Expand All @@ -213,7 +213,6 @@ def form_valid(self, form):
if home_user_exists:
error_message = _("User is already a caregiver in this home")
form.add_error("email", error_message)
messages.error(self.request, error_message)

return self.form_invalid(form)

Expand All @@ -224,14 +223,19 @@ def form_valid(self, form):
)
except Exception:
error_message = _("Something went wrong")
form.add_error("email", error_message)
messages.error(self.request, error_message)

return self.form_invalid(form)

return super().form_valid(form)

def form_invalid(self, form):
# Handle the logic when the form is invalid
# For example, return to the form with error messages
return super().form_invalid(form)
def get_success_url(self):
"""Redirect to current page after successful form submission."""
# Get the current view name
view_name = self.request.resolver_match.view_name
# Get the current URL parameters
kwargs = self.request.resolver_match.kwargs
# Construct the success URL
success_url = reverse(view_name, kwargs=kwargs)

return success_url

0 comments on commit e077192

Please sign in to comment.