Django使用模板替代form中的action路径
views.py
def search_form(request):
#pathq = os.path.join(BASE_DIR,"/polls/search/")
return render_to_response('polls/search_form.html')
def search(request):
if 'q' in request.GET:
#print(os.path.join(BASE_DIR,"/polls/search/"))
#pathq = os.path.join(BASE_DIR,"/polls/search/")
return render(request,'polls/search_form.html',{'searchcontent':request.GET['q']})
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
urls.py
from django.urls import path
from . import views
urlpatterns = [
...
path('search_form/', views.search_form, name='search_form'),
path('search/', views.search, name='search'),
path('contact/', views.contact, name='contact'),
]
search_form.html
{% url ‘search’ %}表示在当前app的urls.py中寻找’search’的匹配项
<html>
<head>
<title>Search</title>
</head>
<body>
<!--<form action="http://localhost:8000/polls/search/" method="get">-->
<form action="{% url 'search' %}" method="get">
<!--这里的name="q"会通过Httprequest对象传递到views.py的函数中。然后用Httprequest.GET获取-->
<input type="text" name="q">
<input type="submit" value="Search">
</form>
<div>
{{searchcontent}}
</div>
<div>
<h1>Contact us</h1>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="{% url 'contact' %}" method="post">
<p>Subject: <input type="text" name="subject"></p>
<p>Your e-mail (optional): <input type="text" name="email"></p>
<p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>