Skip to content
Snippets Groups Projects
Commit 0bc5e6ce authored by Roang's avatar Roang
Browse files

Add FormMesssageMixin

With this we can automate the addition of success and failure messages
to general form views.
parent 7f7467df
No related branches found
No related tags found
No related merge requests found
from typing import Any
from django.contrib.messages import ERROR, SUCCESS, add_message
from django.forms import Form
from django.http import HttpResponse
class FormMesssageMixin:
"""
Add a success message on successful form submission.
"""
success_message = ''
success_message_code = SUCCESS
failure_message = ''
failure_message_code = ERROR
def form_valid(self, form: Form) -> HttpResponse:
"""Set a success message on successful form submission.
Args:
form (Form): The form that was submitted.
Returns:
HTTPResponse: The response generated by the parent class.
"""
response = super().form_valid(form)
success_message = self.get_form_message(self.success_message, form.cleaned_data)
if success_message:
add_message(
self.request,
self.success_message_code,
success_message,
)
return response
def form_invalid(self, form):
"""Set a failure message on failed form submission.
Args:
form (Form): The form that was submitted.
Returns:
HTTPResponse: The response generated by the parent class.
"""
response = super().form_invalid(form)
failure_message = self.get_form_message(self.failure_message, form.cleaned_data)
if failure_message:
add_message(
self.request,
self.failure_message_code,
self.get_form_message(self.failure_message, form.cleaned_data),
)
return response
def get_form_message(self, message: str, cleaned_data: dict[str, Any]) -> str:
"""Try to generate a message from the message template.
Args:
message (str): The message template.
cleaned_data (dict[str, Any]): The cleaned data from the form.
Returns:
str: The formatted message.
"""
return message % cleaned_data
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment