1
我正在嘗試構建儀表板並希望根據用戶的選擇更新圖表。例如,如果用戶選擇A公司,並點擊'更新'按鈕,代碼將捕獲該更改,根據新選擇查詢數據並將其再次傳遞到前端。Django - 如何捕獲用戶在前端做出的選擇
我已經能夠編寫大部分代碼,我可以根據選擇查詢數據庫。但我不確定如何捕獲用戶選擇並從前端傳遞給views.py。
型號:
class Airline(models.Model):
name = models.CharField(max_length=10, blank=True, null=True)
code = models.CharField(max_length=2, blank=True, null=True)
class FinancialData(models.Model): # All units in millions
airline = models.ForeignKey(Airline)
financial_year = models.ForeignKey(Year)
mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2)
regional_revenue = models.DecimalField(max_digits=7, decimal_places=2)
other_revenue = models.DecimalField(max_digits=7, decimal_places=2)
Views.py:
class ListAirlineYearFinancialData(generics.ListAPIView):
serializer_class = FinancialDataSerializer
airline_id = Airline.objects.filter(pk=1) # pk=1 is just a placeholder, but want to change based on selection
queryset = FinancialData.objects.filter(airline_id=airline_id)
queryset_filtered = queryset.filter(financial_year_id=1)
def airline_dashboard(request):
airline_list = Airline.objects.all()
year_list = Year.objects.all()
return render(request, 'dashboard/company_page.html', {'airline_list': airline_list, 'year_list': year_list})
def get_queryset(self, *args, **kwargs):
return self.queryset_filtered
Urls.py
url(r'^$', views.ListAirlineYearFinancialData.airline_dashboard, name='airline_dashboard'),
HTML
<form action="" method="GET">
{% csrf_token %}
<select>
{% for airline in airline_list %}
<option>
Primary Key: {{ airline.pk }}
</option>
{% endfor %}
</select>
<select>
{% for year in year_list %}
<option>
Year: {{ year.year }}
</option>
{% endfor %}
</select>
<input type="button" value="Update">
</form>
基本上,我想在這Views.py行代碼來改變基於由用戶選擇:airline_id = Airline.objects.filter(pk=1)
非常感謝Lindow的指導。你太棒了! – Hannan