[Answer]-Django – Can't Initialize Selected Radio Button when using ModelChoiceField with RadioSelect Widget

1👍

It appears this has been answered here before. In my model I used the to_field argument in the creation of the ForeignKey field, but the ModelChoiceField is expecting to use the id when the ‘initial’ value is passed to it. There are several options to fix this in my example including:

  1. Remove the to_field parameter from the ForeignKey field in the model.
  2. When creating the form instance in the view, set the ‘initial’ parameter for the field using the field’s id from the model instance, e.g.,

    form = TestTicketForm(request.POST,
                          instance=ticket_instance,
                          initial={'ticket_type': instance.ticket_type.id)
    
  3. Set the form field’s initial value in the forms __init__() method. Again this uses the field’s id from the model instance. For example:

    class TestTicketForm(ModelForm):
         ticket_type = ModelChoiceField(TicketType.objects.all(), 
                                        widget=RadioSelect, 
                                        empty_label=None)
    
    
    def __init__(self, *args, **kwargs):
        super(TestTicketForm, self).__init__(*args, **kwargs)
    
        if self.instance is not None:
            self.initial['ticket_type'] = self.instance.ticket_type.id
    

Option #1 above would require a schema and data migrations in my database. Options #2 and #3 are similar but I chose option #3 since it makes my view code slightly cleaner.

Leave a comment