2

I am trying to spin first Django project and I am struggling how to pass value to python function from html. Basically, I have 1 placeholder with 3 buttons next to it. I have file.html in templates.

   <form method="POST" action="">
        {% csrf_token %}

        <input type="text" name="name_id" placeholder="placeholder value"/>

        <input type="submit" value="Value 1"/>
        <input type="submit" value="Value 2"/>
        <input type="submit" value="Value 3"/>
    </form>

I am trying to pass placeholder value to views.py. In views.py I have 3 functions. I want to execute only one of them based on value.

Value 1 from file html triggers function 1 in views py Value 2 from file html triggers function 2 in views py Value 3 from file html triggers function 3 in views py

I am not sure how to handle urls.py

All files are in same app/folder

Any help is much appreciated.

1 Answer 1

1

You can work with a name="…" attribute on the submit <button>s:

<form method="POST" action="">
    {% csrf_token %}

    <input type="text" name="name_id" placeholder="placeholder value"/>

    <input type="submit" name="value1"/>
    <input type="submit" name="value2"/>
    <input type="submit" name="value3"/>
</form>

In the view you can then check with:

def some_view(request):
    if request.method == 'POST':
        if 'value1' in request.POST:
            # …
            pass
        elif 'value2' in request.POST:
            # …
            pass
        elif 'value3' in request.POST:
            # …
            pass
Sign up to request clarification or add additional context in comments.

13 Comments

Maybe I dont get it, but I have 3 different functions, not 1. And how do I pass request from html through urls.py?
@thankyou: the some_view is a "dispatcher". In your case, you thus can for each if condition, call a view function that corresponds with the given name passed by the form.
I see. Thank you. But I am still confused. How do I call "some_view" from the html and how do I pass "placeholder value" along with the value of the button?
@thankyou: you define a path(...) that points to some_view, and you let the form make a request to that path.
@thankyou: but you use value="value1"? Why? Normally it should be name="value1", such that it passes that as POST parameter.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.