简体   繁体   English

Django,如何在表单提交时将 HTML 表单值传递给 URL?

[英]Django, How to pass HTML form values to URL upon form submission?

The project have url as follows,该项目有url如下,

 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.我有一个 HTML 表格,在填写并提交它应该将填写的表格数据传递给 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提交表单时,它会在下面给出 URL

http://127.0.0.1:8000/%7Burl?csrfmiddlewaretoken=2RZfZ4cxLB...

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您不必在 urlpatterns 中传递<str:state>参数,只需传递path('post/search',SearchView.as_view(),name='search-data')或任何你想要的,但问题是当你传递像这篇post/<str:state>/这样的参数比你必须在你的表单中指定这个动作也像这样{% url 'search-data' state %}初始你没有任何 Z9ED39E2EA6942 到 53E8从您的表单中获取 state 名称,因此您的代码最终看起来像这样

<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而不是在您的视图中,您必须从request.GET方法中获取它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM