Choices not updated in Django's Multiple Choice Field

Django:1.10

After writing the following article, I found the problem I wrote in "Addition 2016/11/26".

How to generate a query using the IN operator in Django http://qiita.com/nakkun/items/86a94e65fe6785325f54

When creating an input field to select an author in MultipleChoiceField, I got a list of authors that can be selected from the database and passed it to choices, but even if I add an author, it is not reflected on the screen unless the server is restarted.

You can assign it in View, but I want Form to do the Form.

I hadn't studied Python classes yet, so I was wondering if it would be application scope.

When I read the Python book during the year-end and New Year holidays, I see, the values are assigned when the class object is created. In other words, it's a static field in Java.

So, I modified it to substitute choices when creating an instance.

forms.py


class SearchForm(forms.Form):

    author = forms.MultipleChoiceField(label='Author', widget=forms.CheckboxSelectMultiple, required=False)

    def __init__(self, param):
        forms.Form.__init__(self, param)
        self.fields['author'].choices = [(author.id, author.name) for author in Author.objects.all()]

Now, just reloading the browser will reflect the author addition.

Postscript 2017/01/09

I received your comments in the comments and found that it was easier to do.

forms.py


class SearchForm(forms.Form):

    author = forms.ModelMultipleChoiceField(
        label='Author', widget=forms.CheckboxSelectMultiple, required=False,
        queryset=Author.objects.all(), to_field_name='name')

You can do it with just this!

Postscript 2017/01/11

I received further comments. It can now be updated by passing a callable object to choices without using ModelMultipleChoiceField.

forms.py


class SearchForm(forms.Form):

    author = forms.MultipleChoiceField(
        label='Author', widget=forms.CheckboxSelectMultiple,
        choices=lambda: [(author.id, author.name) for author in Author.objects.all()], required=False)

You can do this too!

Recommended Posts

Choices not updated in Django's Multiple Choice Field
Django's auto_now may not be updated