如何从url标签调用django表单字段?

时间:2014-04-09 23:15:08

标签: python django django-forms

我有一个表单,我正在使用它来捕获字段值并进行搜索。 这个想法是使用来自django的“漂亮”网址的呼叫模板:

mypage.com/search_results/hola

问题是我还没有把表单字段作为参数传递给url模板。

Forms.py
class SearchForm(forms.Form):
    place_display = forms.CharField(max_length=100, help_text='Donde Quieres Ir')

views.py
 def search_results(request,place):
 ..

urls.py
urlpatterns = patterns('',
    url(r'^search_results/(?P<place>\d+)/$', views.search_results, name='search_results'),
    ..

如果我使用模板,我应该如何从模板中的url标记调用:

<form class="form-horizontal" action="{% url 'search_results' %}" role="form" method="get">
    <div class="form-group">
        <div class="col-lg-5">
            <label>Lugar</label>
            {{ form.place_display|add_class:"form-control"}}
            {{ form.place_type }}
            {{ form.place_id }}
        </div>
    </div>

   <div class="controls form-inline">
    <div class="form-group">
        <div class="col-lg-2">
             <label>Entrada</label>
            {{ form.fromdate|add_class:"form-control"}}

        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-2">
            <label>Salida</label>
            {{ form.todate|add_class:"form-control"}}
        </div>
    </div>
    </div>
<br />
<button type="submit" class="btn btn-default">Buscar</button>

我尝试了不同的方式:

action="{% url 'search_results' form.place_display %}"
action="{% url 'search_results' {{form.place_display}} %}"
action="{% url 'search_results' place=form.place_display %}"
etc,etc,etc

1 个答案:

答案 0 :(得分:0)

在表单中填写action='',然后在您的视图中进行重定向;)

以下是视图的外观:

def search_results(request, place):

    if request.method == 'POST':
        place = request.POST.get('place_display','')
        # place_display is the parameter you want, 
        # And '' is the default value if place_display isn't found.


        ### The following return is the thing you want to do, but it is unnatural. 
        ### You can't have an HTML page for any query term a user may search.
        ### What does the 'place' query should actualy do for you?

        return render(request, 'search_results/place', {})

而不是这个回报,您可能真正想要做的是以下内容:

return render(request, 'search_results.html', {place: 'place'})