abautista
abautista

Reputation: 2780

How to read the contents of drop-down menus in Django?

I have two drop-down menus and I want to retrieve its values to use them as variables to filter the retrieved data from an internal Web API.

Dropdown menus

Views.py

# I want to retrieve the year and week number, so I can use them as values in my filter
def filter():
    filters = {"filter": {
        "filters": [{
            "field": "DateTime",
            "operator": "gte",
            "value": "2017-07-23 23:59:59"
        }, {
            "field": "DateTime",
            "operator": "lte",
            "value": "2017-08-18 23:59:59"
        }],
        "logic": "and"
    }}

I did not use Django forms because I am not holding any other data than the years and I am generating the number of weeks, however, if you consider that it might be useful to use Django forms to facilitate the data handling then write your point of view, I want to make this web app better.

header.html

<form method="POST"> {% csrf_token %}
    <h6>Select year</h6>
    <select name="select_year">
      <option value = "2016" >2016</option>
      <option value = "2017"> 2017</option>
      <option value = "2018"> 2018</option>
    </select>
      <h6>Select week</h6>
      <select name="select_week">
      <!--range is not supported: the spaces represent the number of weeks -->
     {% for week in "                                                    " %}
        <option value="{{forloop.counter}}">{{forloop.counter}}</option>
    {% endfor %}
    </select>
    <button type="submit">Search</button>
</form>

Caveat: I am concerned that the code to generate the week numbers is totally incorrect because it is not the right solution and I have read the following posts Numeric loops in Django templates, Iterate number in for loops but this is out off topic and my priority is to get the values of these two dropdown menus.

Upvotes: 0

Views: 1244

Answers (1)

Sachin
Sachin

Reputation: 3674

Solution:

def your_view(request):
    if request.method == 'POST':
        year = request.POST.get('select_year', None)
        week = request.POST.get('select_week', None)

        # rest of the code

Add an action to the form in html template and a urlpattern for it in Django, which is handled by your_view method.
The request object stores the data in POST dictionary, with keys based on html tag names.

You can then pass these values to your filter method to format the filters as you wish to.

Note: It's probably better to use Django Forms as it saves writing the HTML code and sanitize the values too.

Ref: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST

Upvotes: 2

Related Questions