[英]Passing FormView data from CBV to another CBV
這是我的模型:
class DataEm(models.Model):
title = models.CharField(max_length=255, blank=True)
這是我的基本搜索表單:
from django import forms
class SearchForm(forms.Form):
App_title = forms.CharField(max_length=256)
這就是我在該區域中的views.py的樣子:
class ResultsView(generic.ListView):
model = DataEm
template_name = 'explorer/results.html'
context_object_name = 'apps'
class SearchView(generic.FormView):
template_name = 'explorer/search.html'
form_class = sf.SearchForm
success_url = '/explorer/results/'
def get_data(form):
name = form.cleaned_data['App_title']
apps = DataEm.objects.filter(title__contains=name)
return apps
這分別是我的search.html和results.html模板:
<form action="" method='post'>{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Search' />
</form>
和:
<table>
{% for app in apps %}
<tr>
<td>{{ app.title }}</td>
<td>{{ app.price }}</td>
</tr>
{% endfor %}
</table>
當用戶提交表單時,我想運行get_data()方法以根據其關鍵字獲取搜索結果,並將頁面重定向到results.html頁面,該頁面將顯示搜索結果。
顯然,第一個窗體和第二個視圖之間沒有任何聯系,我一直在嘗試通過從SearchView.form_valid()調用redirect()快捷方式或render_to_response來解決此問題,但它不起作用。 現在發生的事情是,提交后,將調用success_url並將result.html加載整個數據庫中的內容。
唯一可行的解決方案是侵入form_valid()並調用get_data()並將結果寫入數據庫的一個單獨表中,該表針對ResultsView。 但這在我看來是愚蠢的。 我敢肯定,有一種更專業的方法可以在基於類的視圖之間傳遞數據。
為什么不使用相同的視圖並簡單地覆蓋get_queryset方法?
編輯:據我所知,您有一個單獨的SearchView,通過這種方式,您應該將表單的操作從空更改為{% url "name.of.your.resultsview" %}
並覆蓋SearchView的get_queryset。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.