简体   繁体   English

使用表单在Django模板中传递url参数

[英]passing url parameter in django template using form

I'm writing a page that takes an id and finds a user that matches that id. 我正在写一个带有ID并找到与该ID匹配的用户的页面。 this is the URL pattern that I wrote in urls.py : 这是我在urls.py中编写的URL模式:

re_path(r'^users/id=(?P<username>[0-9]{9})$' , views.usershow , name = 'usershow') ,

I want to pass username using forms and so I wrote this in templates : 我想使用表单传递用户名,所以我在模板中写了这个:

<form action="{% url 'CMS:usershow' %}" method="GET" >
{% csrf_token %}
<input name="id" type="number" placeholder="search">
<button type="submit">find</button>
</form>

but it shows me this error : 但这告诉我这个错误

Reverse for 'usershow' with no arguments not found. 1 pattern(s) tried: ['dashboard/users/id=(?P<username>[0-9]{9})$']

How can I pass it using forms with this URL pattern? 如何使用具有此URL模式的表单传递它?

First, make sure CMS app's urls.py is having the path. 首先,请确保CMS应用的urls.py具有路径。

Second, pass user id value as shown below: 其次,传递用户ID值,如下所示:

<form action="{% url 'CMS:usershow' user_id %}" method="GET" >

REF: https://docs.djangoproject.com/en/2.1/topics/http/urls/#s-reverse-resolution-of-urls 参考: https : //docs.djangoproject.com/zh-CN/2.1/topics/http/urls/#s-reverse-resolution-of-urls

That's not how forms work. 表单不是这样工作的。 Remove the username from the pattern: 从模式中删除用户名:

path(r'^users/' , views.usershow , name = 'usershow') ,

and in the view get the value from the request; 并在视图中从请求中获取值;

username = request.GET["id"]

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

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