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

Time:04-29

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?

CodePudding user response:

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.

  • Related