I have a form set up as follows. Form class has radio group:
class BookForm(ModelForm):
class Meta:
widgets = {
'book_type': RadioSelect(attrs={'class': 'horizontal-radiogroup'}),
}
And in init, the choices are set dynamically:
self.fields['book_type'].queryset = available_book_types
Where available_book_types
is a queryset that is filtered based on conditions.
I need to dynamically set a value in the radio group as checked in the template.
I tried the following:
self.fields['book_type'].initial = available_book_types.filter(category='Fiction').first()
But it didn't work. Is there a way to achieve this, or do I need to handle this with JavaScript in the frontend?
Edit: I use the form as follows:
Called from view:
def book_get_response(request, book=None)
...
initial_data = request.GET
form = BookForm(instance=book, initial=initial_data)
return {'form': form}
In init I have the code I originally posted.
I have actually managed to get it working if I set it before creating form, in the initial_data
dict. It works if I set the the book:
initial_data['book_type'] = Book.objects.filter(category='Fiction').first()
However, if I print the initial
of the field in init, it shows up as None, yet the radio button is checked correctly in the template. Why is this?