Coverage for baibu/chat/forms.py: 100%
31 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-10-06 13:07 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-10-06 13:07 +0000
1from django import forms
2from django.conf import settings
3from django.core.validators import MaxLengthValidator
4from django.utils.translation import gettext_lazy as _
7class MessageForm(forms.Form):
8 content = forms.CharField(
9 label=_("Message"),
10 widget=forms.Textarea(attrs={"rows": 2, "placeholder": _("Write a message")}),
11 )
12 idempotency_key = forms.CharField(widget=forms.HiddenInput, max_length=64)
14 def __init__(self, *args, **kwargs):
15 super().__init__(*args, **kwargs)
16 self.fields["content"].max_length = settings.CHAT_MAX_MESSAGE_CHARACTERS
17 self.fields["content"].validators.append(MaxLengthValidator(settings.CHAT_MAX_MESSAGE_CHARACTERS))
18 self.fields["content"].widget.attrs["maxlength"] = settings.CHAT_MAX_MESSAGE_CHARACTERS
21class ReportForm(forms.Form):
22 reason = forms.ChoiceField(label=_("What is wrong with this reply?"), widget=forms.RadioSelect)
23 note = forms.CharField(
24 label=_("Anything else we should know? (optional)"),
25 required=False,
26 max_length=500,
27 widget=forms.Textarea(attrs={"rows": 3}),
28 )
30 def __init__(self, *args, **kwargs):
31 from .models import ChatFlag
33 super().__init__(*args, **kwargs)
34 self.fields["reason"].choices = ChatFlag.Reason.choices
37class VoiceForm(forms.Form):
38 """A recorded voice message. The size and format are checked here; the
39 audio itself is only read by the speech-to-text provider."""
41 audio = forms.FileField(label=_("Voice message"))
42 idempotency_key = forms.CharField(widget=forms.HiddenInput, max_length=64)
44 def clean_audio(self):
45 audio = self.cleaned_data["audio"]
46 if audio.size > settings.CHAT_VOICE_MAX_BYTES:
47 raise forms.ValidationError(_("The recording is too long."), code="too_large")
48 content_type = (audio.content_type or "").split(";")[0].strip().lower()
49 if content_type not in settings.CHAT_VOICE_CONTENT_TYPES:
50 raise forms.ValidationError(_("This audio format is not supported."), code="content_type")
51 audio.clean_content_type = content_type
52 return audio