我现在正在学习Django,我试着在网站上添加一个下拉列表。该网站现在将显示一个游戏列表。下拉列表有不同的平台,我想在用户选择一个平台后更改游戏列表。我该怎么办?
在form.py
class platformSelectForm(forms.Form):
platformsList = (
('all', 'Please Select'),
('NS', 'Nintendo Switch'),
('PS4', 'PlayStation4'),
('PS5', 'PlayStation5'),
('XBO', 'Xbox One'),
('XS', 'Xbox Series S/X'),
);
platforms_Select = forms.ChoiceField(widget = forms.Select, choices = platformsList, required = False);在view.py
class showGameLists(TemplateView):
template_name = "showList/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs);
platformSelect = platformSelectForm(self.request.POST or None);
context['platformSelect'] = platformSelect;
games = getGames(nowDay.year, nowDay.month, platforms);
context['games'] = games;
context['year'] = nowDay.year;
context['month'] = calendar.month_name[nowDay.month];
context['prevMonth'] = prevMonth(nowDay);
context['nextMonth'] = nextMonth(nowDay);
return context在urls.py:
from django.urls import path;
from .views import showGameLists;
urlpatterns = [
path('', showGameLists.as_view(), name='home')
]在home.html:
<form method = 'POST' action = '/'>
{% csrf_token %}
{{ platformSelect.as_p }}
<input type='submit' value='Submit' />
</form>
{% for game in games %}
<div>
<span><h2>{{game.0}}</h2>
<p>Release Date: {{ game.1 }}, Metacritic: {{ game.3 }}</p>
<p>Platform: {% for platform in game.2 %}{{ platform }}/{% endfor %}</p>
{% if game.4 %}
<img src={{game.4}} width="367" height="204">
{% endif %}
</div>
{% endfor %}现在,我可以显示list and submit按钮。但我尝试了很多方法来从下拉列表中获取值,但这也让我错了:
[17/Jan/2021 11:15:29] "POST / HTTP/1.1" 405 0
Method Not Allowed (POST): /
Method Not Allowed: /发布于 2021-01-18 02:23:07
你得到了一个Method Not Allowed (POST)错误,因为你正在使用一个TemplateView来提交一个POST请求,你应该像这样使用FormView:
class showGameLists(FormView):
template_name = "showList/home.html"
form_class = platformSelectForm # pass your form class here
def form_valid():
form.save() # process form submit
return redirect('view_to_redirect_to')https://stackoverflow.com/questions/65764293
复制相似问题