Ivory
Ivory

Reputation: 61

HTML name/value button attribute not being sent via POST request to server

I am currently using HTMX and Django to process button clicks within a table that adds the selected item to a list. I am trying to use the name/value HTML attributes to send to the backend with the value being dynamic based on the database information. I have the following form code:

<form action="" method="post">
    {% csrf_token %}
    <button hx-post="{% url 'add-analysis' %}" hx-target="#analysis-list" type="submit" name="projectChoice" value="{{project.project_title}}">Add</button>
</form>

in my Views.py I am trying to parse the data with the following code:

def add_analysis(request):
    proj_name = request.POST.get("projectChoice")
    print(list(request.POST.items()))
    print(request.data())
    return render(request, 'includes/analysis-list.html', {"selected_projects" : proj_name})

This returns None however. To debug this I tried listing all of the POST requests to the server with the following:

print(list(request.POST.items()))

However this only returns the CSRF token, what am I doing wrong here?

Upvotes: 1

Views: 631

Answers (2)

Neil McGuigan
Neil McGuigan

Reputation: 48287

try

<button hx-vals='{"projectChoice":"{{project.project_title}}"}' ... >Add</button>

or

<button hx-vals='js:{"projectChoice": event.target.value}' ... >Add</button>

Upvotes: 1

user6905499
user6905499

Reputation:

htmx sends the button value with the posted data when the request attribute hx-post is placed on the form itself.

<form hx-post="/form" hx-target="#result">
    <button name="submit1" value="foo" type="submit">Submit 1 (foo)</button>
    <button name="submit2" value="bar" type="submit">Submit 2 (bar)</button>
</form> 

Here's a live example https://codepen.io/jreviews/pen/PoEJYMX

In your case you can try to do something different on the server side depending on the button that was used to submit the form.

Upvotes: 0

Related Questions