0

I have been trying to set a default value on a ModelChoiceField for days and it just will not work (this is a form which the user can edit after creating it).. here is my code:

views.py

@login_required(login_url='/admin/login')
def edit_keydef(request, id):

    data = {'title': 'View or Edit Key Definition'}
    template = 'generate_keys/edit_keydef.html'

    keydef = get_object_or_404(KeyDefinition, pk=id)

    if request.method == "POST":
        keydetails_form_instance = KeyDefDetailsForm(request.POST, instance=keydef)

        if 'Save' in request.POST:
          # stuff that saves the edited form.
      

        if 'Generate' in request.POST:
          # stuff that generates a key for the user  
    else:
        keydetails_form_instance = None
        if not id:
            keydetails_form_instance = KeyDefDetailsForm()
        else:
            # Retrieve a previously saved form.
            try:
                keydetails = KeyDefinition.objects.get(pk=id)
                keydetails_form_instance = KeyDefDetailsForm(keydetails.to_dict(),
                                             instance = keydetails)
            except KeyDefinition.DoesNotExist as e:
                return redirect('/record_does_not_exist')

    # Form instance has been saved at this stage so update the variant list.
    keydetails_form_instance.update_variants(keydef)

    keydetails_form_instance.update_available_hosts(keydef)

    data['form'] = keydetails_form_instance
    data['set_product_options_url'] = reverse_lazy('set_product_options', kwargs={'id':id})

    return render(request, template, data)

forms.py

class KeyDefDetailsForm (ModelForm) :

    def __init__(self, *args, **kwargs) :
        super(ModelForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.fields['version'].widget.attrs['class'] = "major_minor"
        self.fields['available_hosts'].default = self.fields['host_label']

    def update_variants(self, keydef_obj):
        # some code that updates the feature_variant field
    
    def update_available_hosts(self, keydef_obj):
        print(keydef_obj.host_label)
        # only show hosts that have been created by this user
        self.fields.update({
            'available_hosts': forms.ModelChoiceField(
                empty_label=None,
                widget=Select(),
                queryset = AvailableHosts.objects.filter(host_developer_email=keydef_obj.developer_email),
                required = False,                
                label = "Available Hosts"
            )
        }) 

    class Meta :
        model = KeyDefinition
        fields = '__all__'
        widgets = {
            'customer_name' : TextInput(),
            'host_method' : TextInput(),
            'issue_date' : TextInput(attrs={'type':'date'}),
            'expiry_date': TextInput(attrs={"type":"date"}),
            'available_hosts' : Select(),
            'country' : Select(),
            'feature' : Select(),
            'activation_request' : HiddenInput(),
            'hostid_provision' : HiddenInput(),
        }

My problem is that I want to display a default value on the Available Hosts and hence why I have the line self.fields['available_hosts'].default = self.fields['host_label'] but this doesn't work unless I set empty_label="some string".. which is not what I want - I want the empty_label=None. However, with empty_label=None, the default value ends up being the one above self.fields['host_label'] -- I am so confused!!

Sorath
  • 543
  • 3
  • 10
  • 32

1 Answers1

0

initial should do the trick

form = YourForm(initial = {'available_hosts': id_of_default})

Django, ModelChoiceField() and initial value https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#providing-initial-values

David Wenzel
  • 251
  • 1
  • 7
  • I am struggling to understand why I need to provide the id when the value I want to be the default is self.fields['host_label'] – Sorath Jul 08 '22 at 15:19
  • the id is used to select the element with the corresponding - take a look at to_field_name https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield - maybe even the .default value is sufficient then – David Wenzel Jul 08 '22 at 17:30