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?
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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.
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
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:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With