Search code examples
djangodjango-modelsdjango-formsmodelformdjango-widget

How to override the default value in dropdown list


In my web application, i have a drop-down list created using ModelForm which is rendering well, however, i can't set default text like "Choose One Option" or "Select One", rather its showing the default "----" which I would love to override

I have tried using forms.ChoiceField in my widgets but its still not making any difference

from django import forms
from . import models
from .models import FacultyData

class DepartmentCreationForm(forms.ModelForm):

class Meta:
    model = models.DepartmentData
    fields = ['fid', 'dept_name']

    data = []
    #data.append((None, 'select one'))
    data.append(('20', "---Choose One---"))
    CHOICES = FacultyData.objects.all()

    for v in CHOICES:
        # fname = "%s -- $%d each" % (v.faculty_name, v.created_on)
        data.append((v.id, v.faculty_name))
widgets = {
        'fid': forms.Select(attrs={'class': 'form-control'}),
        'dept_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Department Name'})
   }

I expect the default output to be "Select One" but the actual output is "-----"


Solution

  • Try this :

        class YourForm(forms.ModelForm):
              your_field_name = forms.ModelChoiceField(queryset=FacultyData.objects.all(),empty_label="Select One")
    
             class Meta:
               model = DepartmentData
               fields = ("__all__")
               widgets = {  something   }
    

    If it dont work show your model