0

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_datadict. It works if I set the the book:

initial_data['book_type'] = Book.objects.filter(category='Fiction').first()

However, if I print the initialof the field in init, it shows up as None, yet the radio button is checked correctly in the template. Why is this?

user3553653
  • 127
  • 1
  • 8

1 Answers1

0

I have found the answer. Apparently, the issue was that I tried setting the initial value after calling super. Before this the fields attribute is not accesable, so the solution was to use

self.initial['book_type'] = Book.objects.filter(category='Fiction').first()

Also discussed here: Initial value in form's __init__ for the model with generic relation

user3553653
  • 127
  • 1
  • 8