Jed
Jed

Reputation: 678

Can't get form data in view function: Django

I need to submit a string to a view function via a dropdown menu and submit button.

in my template I have:

<form action="{% url 'exec_task' %}" method="post">
    {% csrf_token %}
    <select id="select_task" form="select_task" name="select_task">
        {% for task in available_tasks %}
          <option id="selected_task" value="{{ task }}">{{ task }}</option>
        {% endfor %}
    </select>
    <input class="button" type="submit" value="Run Selected Task">
</form>

in my view function I have:

def exec_task(request):
  if request.method == 'POST':
    task = request.POST.get('select_task')
    print(task)
    getattr(tasks, task)(0)
  return redirect('management')

The print(task) always comes out as None, which generates an error when I try to call it via getattr in the next line.

I've read through all the questions and tutorials I can find on this and I don't know what I'm doing wrong, but when I print the request.POST object, all I get is the csrf token. The QueryDict has nothing else in it.

Any ideas?

Upvotes: 2

Views: 1044

Answers (1)

Anup Yadav
Anup Yadav

Reputation: 3005

As discussed in comments please remove

form="select_task" from select tag.

So final select tag / html would be.

<form action="{% url 'exec_task' %}" method="post">
    {% csrf_token %}
    <select id="select_task" name="select_task">
        {% for task in available_tasks %}
          <option id="selected_task" value="{{ task }}">{{ task }}</option>
        {% endfor %}
    </select>
    <input class="button" type="submit" value="Run Selected Task">
</form>

Upvotes: 1

Related Questions