Search


Matching states: n/a

<!-- unicorn/templates/unicorn/search.html -->
<div>
    <label>Search typeahead</label><br />
    <input type="text" unicorn:model="state" placeholder="State name" id="state-name"></input>

    <p>
        Matching states:

        {% if states %}
        <ul>
        {% for s in states %}
        <li>{{ s }}</li>
        {% endfor %}
        </ul>

        <button unicorn:click="clear_states">Clear result</button>
        {% else %}
        n/a
        {% endif %}
    </p>
</div>
# unicorn/components/search.py
from django_unicorn.components import UnicornView


class SearchView(UnicornView):
    state = ""

    ALL_STATES = (
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        "Colorado",
        "Connecticut",
        "Delaware",
        "Florida",
        "Georgia",
        "Hawaii",
        "Idaho",
        "Illinois",
        "Indiana",
        "Iowa",
        "Kansas",
        "Kentucky",
        "Louisiana",
        "Maine",
        "Maryland",
        "Massachusetts",
        "Michigan",
        "Minnesota",
        "Mississippi",
        "Missouri",
        "Montana",
        "Nebraska",
        "Nevada",
        "New Hampshire",
        "New Jersey",
        "New Mexico",
        "New York",
        "North Carolina",
        "North Dakota",
        "Ohio",
        "Oklahoma",
        "Oregon",
        "Pennsylvania",
        "Rhode Island",
        "South Carolina",
        "South Dakota",
        "Tennessee",
        "Texas",
        "Utah",
        "Vermont",
        "Virginia",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming",
    )

    def clear_states(self):
        self.state = ""

    def states(self):
        if not self.state:
            return []

        return [s for s in self.ALL_STATES if s.lower().startswith(self.state.lower())]

    class Meta:
        exclude = ("ALL_STATES",)