mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-04-24 01:28:42 +02:00
initial commit
This commit is contained in:
46
app/apps/transactions/fields.py
Normal file
46
app/apps/transactions/fields.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import datetime
|
||||
|
||||
from django import forms
|
||||
from django.db import models
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from apps.transactions.widgets import MonthYearWidget
|
||||
|
||||
|
||||
class MonthYearField(models.DateField):
|
||||
def to_python(self, value):
|
||||
if value is None or isinstance(value, datetime.date):
|
||||
return value
|
||||
|
||||
try:
|
||||
# Parse the input as year-month
|
||||
date = datetime.datetime.strptime(value, "%Y-%m")
|
||||
# Set the day to 1
|
||||
return date.replace(day=1).date()
|
||||
except ValueError:
|
||||
raise ValidationError("Invalid date format. Use YYYY-MM.")
|
||||
|
||||
def formfield(self, **kwargs):
|
||||
kwargs["widget"] = MonthYearWidget
|
||||
kwargs["form_class"] = MonthYearFormField
|
||||
return super().formfield(**kwargs)
|
||||
|
||||
|
||||
class MonthYearFormField(forms.DateField):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.input_formats = ["%Y-%m"]
|
||||
|
||||
def to_python(self, value):
|
||||
if value in self.empty_values:
|
||||
return None
|
||||
try:
|
||||
date = datetime.datetime.strptime(value, "%Y-%m")
|
||||
return date.replace(day=1).date()
|
||||
except ValueError:
|
||||
raise ValidationError("Invalid date format. Use YYYY-MM.")
|
||||
|
||||
def prepare_value(self, value):
|
||||
if isinstance(value, datetime.date):
|
||||
return value.strftime("%Y-%m")
|
||||
return value
|
||||
Reference in New Issue
Block a user