Django使用模板替代form中的action路径

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>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值