Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, how to remove the blank choice from the choicefield in modelform?

Tags:

forms

django

I created a model with a foreign key in it:

class Book(models.Model):     library = models.ForeignKey(Library, null=False, blank=False)     ... 

and then I created a form with a ModelForm to display to the users:

class BookSubmitForm(ModelForm):     class Meta:         model = Book 

and when I display the page with the form I get the Library choices but also the blank (--------) choice that comes by default.

I thought by having null=False and blank=False in the model that would get rid of that blank choice in the ModelForm but no. What can I do to only have actual choices in the list and not that one?

like image 232
Bastian Avatar asked Jan 10 '12 05:01

Bastian


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do I customize Modelan in Django?

To create ModelForm in django, you need to specify fields. Just associate the fields to first_name and lastName. Under the Meta class you can add : fields = ['first_name','lastName']. @Shishir solution works after I add that line. or you can try solution in Jihoon answers by adding vacant fields.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is ChoiceField in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.


2 Answers

See ModelChoiceField. You have to set empty_label to None. So your code will be something like:

class BookSubmitForm(ModelForm):     library = ModelChoiceField(queryset=Library.objects, empty_label=None)      class Meta:         model = Book     

EDIT:changed the field name to lower case

like image 115
Ilya Avatar answered Oct 10 '22 17:10

Ilya


self.fields['xxx'].empty_label = None would not work If you field type is TypedChoiceField which do not have empty_label property. What should we do is to remove first choice:

class BookSubmitForm(forms.ModelForm):      def __init__(self, *args, **kwargs):         super(BookSubmitForm, self).__init__(*args, **kwargs)          for field_name in self.fields:             field = self.fields.get(field_name)             if field and isinstance(field , forms.TypedChoiceField):                 field.choices = field.choices[1:] 
like image 26
Mithril Avatar answered Oct 10 '22 17:10

Mithril