简体   繁体   中英

Django ChoiceField - How to show the currently selected value?

I have a Django ChoiceField called states defined in my forms class.

class StateForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(StateForm, self).__init__(*args, **kwargs)
        self.fields['states'] = forms.ChoiceField(widget=forms.Select,
                                 choices=OPTIONS_STATE)
        self.initial['states'] = 'Any'

I also set the initial value to 'Any', since I want the dropdown say 'Any' by default.

In my views.py , get_context_data() function, I add it to the context that's sent to the html.

        context['state_form'] = StateForm()

In my html, I can render the dropdown using Django's special language

{{ state_form.states }}

So far so good. I see a dropdown in my page, and the default value is 'Any'. I can click on it to select other values, at that point my javascript code would send a HTTP request based on my form. It would reload the page with filtered data. I was able to get all of that done.

The problem is that once the page reloads, the dropdown still says 'Any'. I want the dropdown to show the previously selected data. But I'm not sure how.

I would recommand you to store that value in session/cookie and then in javascript change the default value of the dropdown based on that session/cookie information.

More about cookies you can find in django doc: https://docs.djangoproject.com/en/1.9/topics/http/sessions/

When you redirect to a new URL, pass the selected state as a GET parameter to the URL. Eg:

url = 'http://example.com/some-page/?state=Texas'

Then on the next page, use JS to read the state parameter and set the value of the dropdown accordingly. Or you can pass the state as context variable in the next URL's view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM