Home > Software engineering >  Django, How to pass HTML form values to URL upon form submission?
Django, How to pass HTML form values to URL upon form submission?

Time:12-24

The project have url as follows,

 path('post/<str:state>/',SearchView.as_view(),name='search-data')

I have a HTML form, upon filling and submitting it supposed to pass filled form data to URL.

<form action={% url 'search-data'%} method="get" >
      {% csrf_token %}
     
      <input type="text"  name="fname">  

But it does not work as supposed to be.

When form submitted it gives below URL

http://127.0.0.1:8000/{url?csrfmiddlewaretoken=2RZfZ4cxLB...

CodePudding user response:

You don't have to pass <str:state> argument in your urlpatterns just pass path('post/search',SearchView.as_view(),name='search-data') or whatever you want but problem is when you pass an argument like this post/<str:state>/ than you have to specify that in your form action also like this {% url 'search-data' state %} initialy you don't have any state so that's why you have to get the state name from your form so finnaly your code look like this

<form action={% url 'search-data'%} method="get" >
      {% csrf_token %}
     
      <input type="text"  name="fname">  
      <input type="submit" value="search">
</form>

and than in your views you've to get it from request.GET method like this

def search(request):
    state = request.GET.get('fname', None)
    .... do whatever you want 
    return response_or_data
  • Related