15👍
If you pass a QuerySet
object as an initial value and if widget=forms.CheckboxSelectMultiple
, then the check boxes are not checked. I had to convert the QuerySet
object to a list, and then the check boxes were checked:
YourForm(
initial={
"multi_field": [
cat for cat in Category.objects.all().values_list("id", flat=True)
]
}
)
20👍
You can pass it the “initial” setting from your view. For example:
form = FormUsingCategory(initial={'category':querysetofinitialvalues})
The tricky part is that you must have the right queryset. Just like the seed values, it must be of Category.objects.filter(…) – anything else won’t work.
- [Django]-How to validate an Email address in Django?
- [Django]-Set Django IntegerField by choices=… name
- [Django]-How to query as GROUP BY in Django?
13👍
Either set initial when you create form instance or set field initial in form init
def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.fields["category"].initial = (
Category.objects.all().values_list(
'id', flat=True
)
)
If you just want to change the text when no field selected you can set empty_label property. https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField.empty_label
- [Django]-Display field choice as part of model string name
- [Django]-How Can You Create an Admin User with Factory_Boy?
- [Django]-Django Shell No module named settings
0👍
I needed something similar in admin and in ModelForm i just did something like:
def __init__(self, *args, **kwargs):
super(CategoryAdminForm, self).__init__(*args, **kwargs)
self.initial['category'] = list(Category.objects.filter(name=<whatever_you_need>))
and it worked fine for me
- [Django]-Django – query filter on manytomany is empty
- [Django]-Django equivalent of PHP's form value array/associative array
- [Django]-403 Forbidden error with Django and mod_wsgi