This repository has been archived on 2026-03-30. You can view files and clone it, but cannot push or open issues or pull requests.
RepApp/repapp/email_interface/forms.py

54 lines
1.6 KiB
Python
Raw Normal View History

2023-08-30 19:19:36 +00:00
import logging
from bs4 import BeautifulSoup
from django import forms
from django.utils.translation import gettext_lazy as _
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from .models import Message
logger = logging.getLogger(__name__)
class MessageForm(forms.ModelForm):
"""
A form for creating new messages.
"""
mail_text = forms.CharField(
label=_("Text content"), required=False, widget=forms.Textarea)
use_mail_text = forms.BooleanField(
label=_('Use text content?'), required=False)
class Meta:
model = Message
fields = ['receiver', 'summary', 'html_content']
widgets = {'html_content': CKEditorUploadingWidget()}
2023-08-31 13:21:38 +00:00
def clean_mail_text(self):
text = self.cleaned_data["mail_text"]
use_text = self.data["use_mail_text"]
logger.debug(
'MessageForm clean_mail_text: use text: %r, text: %s', use_text, text)
if use_text and not text:
2023-08-30 19:19:36 +00:00
raise forms.ValidationError(
_("Mail text cannot be empty if it is used!"))
2023-08-31 13:21:38 +00:00
return text
2023-08-30 19:19:36 +00:00
def save(self, commit: bool = True):
message = super().save(commit=False)
2023-08-31 13:21:38 +00:00
if self.cleaned_data['use_mail_text']:
2023-08-30 19:19:36 +00:00
message.text_content = self.cleaned_data['mail_text']
else:
# convert HTML content to text content
soup = BeautifulSoup(
self.cleaned_data['html_content'], features='html.parser')
message.text_content = soup.get_text('\n')
if commit:
message.save()
return message