How to change ModelChoiceField on a modelform


I am building a feature to reserve a timeslot when making an appointment.

I have two models

class Timeslot(models.Model):
    start_time = models.DateTimeField()

    def __str__(self):
        return f'{self.start_time.astimezone(atlantic_timezone).strftime("%d %b, %I:%M%p")}' \
               f' ({self.start_time.astimezone(current_timezone).strftime("%H:%M")} CEST)'

class Appointment(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=255)
    phone_number = models.CharField(max_length=255)
    email = models.EmailField()
    time_slot = models.OneToOneField(Timeslot, on_delete=models.SET_NULL, null=True)

and my model form:

class AppointmentForm(forms.ModelForm):

    amount = forms.CharField()

    class Meta:
        model = Appointment
        exclude = ['created_at']

however, I would like to change the default ModelChoiceField selection to be a date picker, using the available date from the start_time field in TimeSlot.

How can I achieve this?



With a model form, you can identify a widget to use for each field using the widgets attribute in the Meta class. See Overriding the default fields in the docs.

1 Like