Search code examples
djangoform-fields

How to make a nested field with mixed type options?


I'm making a website to manage some kind of schedule.

I looked into calendars and the like and found this form from google's calendar to be quite what I want. Google Calendar Reminder Interface

The thing is I'm having a hard time figuring out how to solve the Finaliza field. I have a Reminder model, but... Should I make a column for each option and play up with the form widget? Is there some canned solution I can use?


Solution

  • Why don't you just add the columns to your model:

    finalize_type = models.CharField(choices=(('Never', ''), ('Repetitions', ''), ('Date', '')))
    finalize_repetitions = models.IntegerField()
    finalize_date = models.DateField()
    
    # model clean!
    def clean(self):
         if finalize_type == 'Repetitions':
              # check that there is number in finalize_repetitions
              # raise validation error if not
         elif finalize_type == 'Date':
              # check date on finalize_date
    
         # You should also check if date and repetions aren't set when type == 'Never'
    

    If I remember correctly the model clean fires on save. So if you implement a ModelForm it should be displayed on the forms errors.

    I would also implement a method

    @property
    def next_event()
        """returns date of next repetition, None if finished"""
    

    Hope it helps.