arash daneshgar
arash daneshgar

Reputation: 83

i want to do something on value of a ModelForm before saving in database-django

I'm trying to do something on the value of a ModelForm in Django before saving that on the database. that "something" is changing the value of the DateTime field... I want to take Jalali DateTime from the user in the form and in the template and do something on that(it's about changing Jalali DateTime to gregorian DateTime) and save gregorian DateTime on the database... where should I do that? in the view or forms? and how?? this is my forms.py (i want do something on datetime field):

class NewEvent(ModelForm):
    class Meta:
        model = Event
        fields = ['user','datetime','work']

and this is my view:

class CreateEventView(CreateView):
    form_class = NewEvent
    template_name = 'app1/new_event.html'

I know how to convert Jalali to gregorian but I don't know where should be doing that

Upvotes: 2

Views: 76

Answers (1)

Ayush Gupta
Ayush Gupta

Reputation: 1227

Change your form to this:

class NewEvent(ModelForm):
    class Meta:
        model = Event
        fields = ['user','datetime','work']

    def clean_datetime(self, *args, **kwargs):
        datetime = self.cleaned_data.get('datetime')

        # write your Jalali to Gregorian conversion logic here and then

        return datetime

Upvotes: 1

Related Questions