首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为django添加下拉列表

为django添加下拉列表
EN

Stack Overflow用户
提问于 2021-01-18 02:13:08
回答 1查看 20关注 0票数 0

我现在正在学习Django,我试着在网站上添加一个下拉列表。该网站现在将显示一个游戏列表。下拉列表有不同的平台,我想在用户选择一个平台后更改游戏列表。我该怎么办?

form.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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:

代码语言:javascript
复制
from django.urls import path;
from .views import showGameLists;

urlpatterns = [
    path('', showGameLists.as_view(), name='home')
]

在home.html:

代码语言:javascript
复制
<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按钮。但我尝试了很多方法来从下拉列表中获取值,但这也让我错了:

代码语言:javascript
复制
[17/Jan/2021 11:15:29] "POST / HTTP/1.1" 405 0
Method Not Allowed (POST): /
Method Not Allowed: /
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-18 02:23:07

你得到了一个Method Not Allowed (POST)错误,因为你正在使用一个TemplateView来提交一个POST请求,你应该像这样使用FormView

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65764293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档