Search code examples
htmldjangotemplatesrequesthref

Send data by href (html) and get it with request function (django)


I have a html page where I looping on model fields.

Html is:

{% for problem in problems_list %}
<p>
    {{ problem.id }} - {{ problem.incident_date }} - {{ problem.incident_specs }} -
    {{ problem.incident_location }} - {{ problem.incident_reason }}
    {% for action in actions_list %}
        {% if action.action_incident_id_id  == problem.id %}
            <form method="post">
                <input hidden name='problem_id' value="{{ problem.id }} ">
                <a class="btn btn-primary" type="submit"
                href="{% url 'ex_action' %}"> Button </a>
<!--    action="{% url 'ex_action' %}"-->
            </form>
        {% endif %}
    {% endfor %}
</p>

{% endfor %}

And here is a ex_action function:

def ex_action(request):
    return render(request, 'problems/ex_action.html', {'actions_list': actions_list})

It works well, but I need to pass a problem.id from for loop into ex_action, and I don't know how to do it.

I tried some constructions like href="{% url 'ex_action'?=problem_id=problem.id %}" and get it by something like request.GET.get('problem_id') or request.GET['problem_id'], but got TemplateSyntaxError on html, none as result on django code or MultiValueDictKeyError. Read a lot of docs\issues, and find what people use ajax\js to solve it, but I don't know how. Please help.


Solution

  • Thanks for Zatigem's answer above (and sorry, for what it took a long time - I tried to apply your answer, and forgot about it), we should use a construction like this: path('ex-action/int:problem_id', views.ex_action, name='ex_action'), passing the problem_id to the form. Thanks a lot again, Zatigem!