html中的多个按钮,相同的视图,不同的值

时间:2018-06-16 21:26:52

标签: python django django-forms django-views

我正在尝试让我的html在HTML页面上显示session.counter。计数器应该增加一个随机数,其增量范围有4个不同的选项(基于按钮)。到目前为止,我已将所有操作路由到同一视图,但我不确定如何将值编码到视图中!我可以在视图中嵌套多个if-checks吗?如果是这样,我需要在每次检查后立即重定向,还是可以在if-checks之后? 编辑:我已经尝试添加隐藏的输入,以使我的视图更有效。我仍然是新手,所以如果你的反馈越具描述性,我就越容易实现变更并理解原因!

这是html:

        <div id="goldCount">
    <h2>Gold Count: {{ session.request.goldCount }}</h2>
</div>

<div id="goldNode">
    <h2>Blood Lotus Master</h2>
    <h5>(earns 50 to 200 gold coins)</h5>
    <form action='/process_gold' method="post">
        {% csrf_token %}
        <input type="hidden" name="earn" value="reap">
        <button type="submit" name="reap">収める - Reap</button>
    </form>
</div>

<div id="goldNode">
    <h2>Shadow Dance Troupe</h2>
    <h5>(earns 35 to 50 gold coins)</h5>
    <form action='/process_gold' method = "post">
        {% csrf_token %}
        <input type="hidden" name="earn" value="weave">
        <button type = "submit" name = "weave">織る - Weave</button>
    </form>
</div>

<div id="goldNode">
    <h2>Necromancy</h2>
    <h5>(earns -200 to 200 gold coins)</h5>
    <form action='/process_gold' method="post">
        {% csrf_token %}
        <input type="hidden" name="earn" value="summon">
        <button type = "submit" name="summon">召喚 - Summon</button>
    </form>
</div>

<div id="goldNode">
    <h2>Clan War!</h2>
    <h5>(earns -2000 to 2000 gold coins)</h5>
    <form action='/process_gold' method="post">
        {% csrf_token %}
        <input type="hidden" name="earn" value="summon">
        <button type="submit" name="war">影の戦争 - Shadow War</button>
    </form>
</div>

,这是views.py文件

    def index(request):
if 'goldCount' not in request.session:
    request.session['goldCount'] = 0
return render(request, 'index.html')

    def process_gold(request):
reap = random.randint(50,200)
weave = random.randint(35,50)
summon = random.randint(-200,200)
war = random.randint(-2000,2000)

print(request.POST)

if request.POST['earn'] == 'reap':
    request.session['goldCount'] += random.randint(50,200)

if request.POST['earn'] == 'weave':
    request.session['goldCount'] += random.randint(35,50)

if request.POST['earn'] == 'summon':
    request.session['goldCount'] += random.randint(-200,200)

if request.POST['earn'] == 'war':
    request.session['goldCount'] += random.randint(-2000,2000)

return redirect('/')

1 个答案:

答案 0 :(得分:0)

如果要将goldCount发送到HTML,则需要使用render_template而不是重定向。将goldCount存储到会话中,然后只需在HTML中调用{{request.session.goldCount}}

此外,正确的if语句将是:

if 'goldCount' not in request.session:
    request.session['goldCount'] = 0