33 lines
966 B
Python
33 lines
966 B
Python
from django import forms
|
|
from django.core.exceptions import ValidationError
|
|
from .models import Item
|
|
|
|
DUPLICATE_ITEM_ERROR = "You've already logged this to your note"
|
|
EMPTY_ITEM_ERROR = "You can't have an empty note item"
|
|
|
|
class ItemForm(forms.Form):
|
|
text = forms.CharField(
|
|
error_messages = {"required": EMPTY_ITEM_ERROR},
|
|
required=True,
|
|
)
|
|
|
|
def save(self, for_note):
|
|
return Item.objects.create(
|
|
note=for_note,
|
|
text=self.cleaned_data["text"],
|
|
)
|
|
|
|
class ExistingNoteItemForm(ItemForm):
|
|
def __init__(self, for_note, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self._for_note = for_note
|
|
|
|
def clean_text(self):
|
|
text = self.cleaned_data["text"]
|
|
if self._for_note.item_set.filter(text=text).exists():
|
|
raise forms.ValidationError(DUPLICATE_ITEM_ERROR)
|
|
return text
|
|
|
|
def save(self):
|
|
return super().save(for_note=self._for_note)
|