Home > Mobile >  Django Help! Form with method post is not callin the action correctly with django url tag need help
Django Help! Form with method post is not callin the action correctly with django url tag need help

Time:11-03

While trying to create a simple search form using method="POST" and action linking to a url that should trigger a view to render a different template I have come across it not working all it does is tag on the csrf to my index url and acts like I am using GET not POST any thoughts on why?

HTML URL:

http://127.0.0.1:8000/bugtracker/?csrfmiddlewaretoken=jdGcvGb8pioQutLhDOL8y6zbK7DW6XSErTYQ8zHOI8W1fAXf8V6NFoFmzXRIvC3d&searched=

View:

    @login_required(login_url='login_register')
    def search_site(request):
    if request.method == "POST":
        searched = request.POST['searched']
        context = {
            'searched': searched
        }
        return render(request, 'bugs/search_site.html', context)
    else:
        return render(request, 'bugs/search_site.html')

URL:

    path('search_site/', views.search_site, name='search_site'),

Search bar template:

    <div >
    <form method="POST" action="{% url 'search_site' %}">
    {% csrf_token %}
    <input  type="search" placeholder="Search for..." aria-label="Search for..." name="searched">
    <button  type="submit"><i ></i></button>
    </form>
    </div>

Search result template:

{% extends 'bugs/base.html' %}
{% block content %}
    <div >
        {% if searched %}
        <h4 >results for {{ searched }}</h4>
        {% endif %}

    </div>
{% endblock %}

I have tried changing method to get, I have tried to change my url and my view to no avail. and removing crf just makes the url tag a ? into the index it seems like it is not calling anything at all.

CodePudding user response:

I can provide two suggestions, first to render outside the else condition, and the second to see searched has any value or not by printing it.

@login_required(login_url='login_register')
def search_site(request):
    if request.method == "POST":
        searched = request.POST['searched']
        print(f"searched value --> {searched}")
        context = {
            'searched': searched
        }
        return render(request, 'bugs/search_site.html', context)
    return render(request, 'bugs/search_site.html')

Search result template:

{% extends 'bugs/base.html' %}
{% block content %}
    <div >
        {% if searched %}
        <h4 >results for {{ searched }}</h4>
        {% else %}
        <p>No value has come.</p>
        {% endif %}

    </div>
{% endblock %}

I also think it should be another template in POST Method check it, you have provided search_site.html may be it is something like search_result.html.

  • Related