1

I have an HTML page with a series of list items. I would like to be able to push a button, read the data in the list, and do a sort of transformation. I thought it would be rather like this example.

However, this format uses the name attribute to get the data and neither a list or list item can have names!

My HTML:

<form action="{% url 'index' %}" method="POST">
    {% csrf_token %}
    <ul id="myList">
        <li id="myId1">First Item</li>
        <li id="myId2">Second Item</li>
    </ul>
    <button type="submit">Submit</button>
</form>

My python:

def index(request):
if request.method == 'POST':
    var = request.POST['myList']
    print(var)
return render(request, "test.html", {})

Is there a way to get items in a list?

Additional Information:

  • Current output is just None.
  • I can grab data like text boxes just fine, those are named items.
  • I have tried a few other suggestions, like var = request.POST.get('myList'), and even started dealing with forms and models but I could only grab data that was IN the model that way, not a <li>.
1
  • Can you print the output of request.POST? Commented Mar 23, 2018 at 23:24

1 Answer 1

5

You have to have input tags with name attributes inside your form for it to submit any data to the server. Just sticking some list items in there will do nothing - HTML forms require inputs.

Something like this might work for you:

<form action="{% url 'index' %}" method="POST">
    {% csrf_token %}
    <ul id="myList">
        <li id="myId1">First Item <input type="hidden" name="mylist[]" value="myid1"></li>
        <li id="myId2">Second Item <input type="hidden" name="mylist[]" value="myid2"></li>
    </ul>
    <button type="submit">Submit</button>
</form>

i.e, insert a hidden input into each item in your list, with name and value attributes, that should then result in something being available in request.POST.getlist('mylist').

Sign up to request clarification or add additional context in comments.

1 Comment

This worked just as I wanted, thank you for the feedback!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.