2👍
Here we go:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField.empty_label
from here:
Django CheckboxSelectMultiple widget adds ——— value to query set
therefore:
self.fields['document_type'].empty_label = None
does the trick.
0👍
Django has to have a way to allow None values to be set for nullable fields (fields with required=False
) and does so by appending an option with an empty value. The same thing happens with Select elements.
Now, for Django to add that option to your Form the document_type
field must be nullable (indeed have required=False
), and I can only assume that somewhere in the definition of the Form you’re setting that option to the field.
PS: If the form is generated automatically for the Model (i.e. you’re using Django’s ModelForm) then the model should have said Field set with blank=True, null=True
, yet that is clearly missing. ModelForm rocks, though, so if you’re not familiar with it, try it out.
UPDATE:
TBH I can’t work out why that’s nullable either, but try setting required=True
manually in the form in the same way that @Alistair specified.
self.fields['document_type'].required = True
Right under the line where you modified that field to set the queryset. I think that should work.
0👍
A work around is to hide it with css:
#id_document_type li:first-child {display:none}
- Save request.POST to database
- Trouble setting-up directories to compile from in Django-Assets / Webassets
- Django: Print out all choices for a models.Model class
- In django, values(*field) doesn't give all values of ForeignKey field with sliced queryset
0👍
As Agustin mentioned, ModelChoiceFields must be set to required in order to remove the blank choice.
def __init__(self, queryset, empty_label="---------",
required=True, widget=None, label=None, initial=None,
help_text='', to_field_name=None, limit_choices_to=None,
*args, **kwargs):
if required and (initial is not None):
self.empty_label = None
else:
self.empty_label = empty_label
Required is set to False by default, so you’ll need to add the following to your init in Document Form
self.fields['document_type'].required=True
- Django form for a model create object of another model
- Gunicorn is not binding my domain by using ".sock" file
- WSGI module and Django settings locations
-1👍
I solved this by adding these parameters to my declaration of my field in my model:
blank=False, default=None
So in this case, you model would look like this:
document_type = models.ForeignKey(DocumentType,
verbose_name="Document Type", blank=False, default=None)
- How to pass both ListView and DetailView as parameters in views.py/urls.py?
- Templets not found error in django
- Django rq scheduler can not enqueue same task twice