如何使用Django模板在HTML的表单操作中向'“current_url”/ submit'提交POST请求?

时间:2022-11-23 17:47:12

Let's say I have many posts and each post has a url example.com/post_id. Also there is a HTML form after this post where one can submit comment. If I had to submit this comment to this url: example.com/submit , then I could just do <form action="submit/" method="post">. But, I want this comment to be submitted to this url: example.com/post_id/submit so that when it's view is called, that view has access to post_id. This is so I can store the entered comment along with post_id in the database. (I can access the request url in view by request.path_info.)

假设我有很多帖子,每个帖子都有一个url example.com/post_id。此帖后还有一个HTML表单,可以提交评论。如果我必须将此评论提交到此网址:example.com/submit,那么我可以执行

。但是,我希望将此注释提交到此url:example.com/post_id/submit,以便在调用视图时,该视图可以访问post_id。这样我就可以将输入的注释与post_id一起存储在数据库中。 (我可以通过request.path_info访问请求URL。)

One approach would be to pass {{request.path}} concatenated with "submit" in the HTML form action in the template. But I am not able to do that. One can do {{value|add:"submit"}}. But how do I put {{request.path}} in place of value?

一种方法是在模板中的HTML表单操作中传递与“submit”连接的{{request.path}}。但我无法做到这一点。可以做{{value | add:“submit”}}。但是如何将{{request.path}}代替值呢?

tl;dr Using django templates, how to I pass post_id/submit url to HTML form action. (Here current url is example.com/post_id.)

tl; dr使用django模板,如何将post_id / submit url传递给HTML表单操作。 (这里的当前网址是example.com/post_id。)

1 个解决方案

#1


1  

It's a bad idea to try and parse/modify the existing URL. But there's no reason to. Your template presumably already has access to the post itself, so you should use this to construct the URL via the normal {% url %} tag.

尝试解析/修改现有URL是个坏主意。但是没有理由。您的模板可能已经可以访问帖子本身,因此您应该使用此模板通过正常的{%url%}标记构建URL。

<form action="{% url "submit_comment" post_id=post.id %}" method="POST">

assuming the post is passed to the template as post and there is a urlconf that looks like this:

假设帖子作为post传递给模板,并且有一个urlconf,如下所示:

url(r'(?P<post_id>\d+)/submit/$', views.submit_comment, name='submit_comment'),

#1


1  

It's a bad idea to try and parse/modify the existing URL. But there's no reason to. Your template presumably already has access to the post itself, so you should use this to construct the URL via the normal {% url %} tag.

尝试解析/修改现有URL是个坏主意。但是没有理由。您的模板可能已经可以访问帖子本身,因此您应该使用此模板通过正常的{%url%}标记构建URL。

<form action="{% url "submit_comment" post_id=post.id %}" method="POST">

assuming the post is passed to the template as post and there is a urlconf that looks like this:

假设帖子作为post传递给模板,并且有一个urlconf,如下所示:

url(r'(?P<post_id>\d+)/submit/$', views.submit_comment, name='submit_comment'),