fceruti
fceruti

Reputation: 2445

Problems with custom time widget

I have a model that has an attribute that referrers to when this object wont be publicly available anymore.

class Story(models.Model):
    ...
    deadline = models.models.DateTimeField()

What I want to do is present to the user the possibility to to set this date but in a very easy way and restricted way. I´ll give the choice of 1-7 days of "active period". So what I´m doing right now is setting a custom form like this:

DAYS_CHOICES = (
    ('1', '1 day'),
    ...
    ('7', '7 days'),
)

class StoryForm(ModelForm):
    fecha_cierre = forms.TypedChoiceField(
       choices=DAYS_CHOICES, widget=forms.Select)

class Meta:
    models = Story

The problem is '1' or '7' are not datetime objects and I really don´t know where to intercept the form submit process so I can change the value with something like this:

datetime.datetime.now() + datetime.timedelta(days=n_days)).strftime('%Y-%m-%d %H:%M:%S')

What is the preferred approach in this kind of situation?

Upvotes: 0

Views: 544

Answers (1)

catavaran
catavaran

Reputation: 45575

You need to exclude deadline field from the form and override save() method:

class StoryForm(ModelForm):

    fecha_cierre = forms.TypedChoiceField(
       choices=DAYS_CHOICES, widget=forms.Select)

    class Meta:
        models = Story
        exclude = ('deadline',)

    def save(self):
        story = super(StoryForm, self).save(commit=False)
        story.deadline = datetime.datetime.now() + \
                         datetime.timedelta(days=self.cleaned_data['fecha_cierre']))
        story.save()
        return story

Upvotes: 1

Related Questions