Django阻止页面刷新

时间:2019-05-20 11:47:49

标签: python django

所以我有两个问题。 我是Django和Python的新手。我用表单构建页面,然后可以在这些字段中输入数据,我接收到的数据会对其执行一些操作,然后将其他变量传递回去,这些变量在单击按钮后显示在div字段下的div中。它实际上正在工作,但是页面刷新,因此我只能看到一秒钟的结果。第二个问题是我必须在按钮上单击两次,以向我显示正确的结果。示例:首先单击按钮,结果显示x,然后使用其他输入,然后单击按钮,结果再次显示x。再次单击按钮后,它显示正确的结果,我该如何解决此问题呢。

您对如何改进此系统有何建议?

我真的很感谢您的帮助。

我的查看文件:

from django.shortcuts import render,redirect
from django.http import HttpResponse
from pages.forms import NameForm

import requests

# Create your views here.

def home_view(request,*args,**kwargs):
    api_key = "RGAPI-9b573263-7b5a-433e-9e82-a973f5db4749"
    name = ""
    tier = ""
    rank = ""
    lp = 0
    if request.method == 'POST':
        form = NameForm(request.POST)

        if form.is_valid():
            summoner = form.cleaned_data["summoner"]
            region = form.cleaned_data["region"]
            url = "https://" + region + ".api.riotgames.com/lol/summoner/v4/summoners/" \
                                 "by-name/" + summoner + "?api_key=" + api_key
            response = requests.get(url).json()
            id = response["id"]
            name,tier,rank,lp = ranklookup(id,region,api_key)
    return render(request,"home.html",{'form' : form,'rank':rank, 'tier' : tier, 'lp' : lp, 'name' : name})





def ranklookup(id,region,api_key):
    rankurl =  "https://" + region + ".api.riotgames.com/lol/league/v4/entries/by-summoner/" + id + "" \
            "?api_key=" + api_key
    rankResponse = requests.get(rankurl).json()
    if rankResponse[0]["queueType"] == "RANKED_SOLO_5x5":
        name = rankResponse[0]["summonerName"]
        tier = rankResponse[0]["tier"]
        rank = rankResponse[0]["rank"]
        lp = str(rankResponse[0]["leaguePoints"])

    else:
        name = rankResponse[0]["summonerName"]
        tier = rankResponse[1]["tier"]
        rank = rankResponse[1]["rank"]
        lp = str(rankResponse[1]["leaguePoints"])
    return name,tier,rank,lp

还有我的HTML文件:

{% extends 'base.html' %}

{% block content %}
<h2> League of Legends Rank lookup</h2> <br>
<div id ="ranklookup"> 
<form id="myform"  method="post">  {% csrf_token %}
{{ form }}
</form>  
<button onclick="showDiv()" type="submit" id="but" form="myform" value="button">Submit</button><br><br>
<div id="showRank">
  This will get replaced
 </div>

<script type="text/javascript">
  function showDiv(){
    var tier = ' {{ tier }}';
    var rank = ' {{ rank }} ';
    var name = ' {{ name }} ';
    var lp = {{ lp}};

    document.getElementById("showRank").innerHTML =  "Name: " + name + "</br> Rank: " + tier + rank + "</br> LP: " + lp;
      }
      </script>
    {% endblock %}"

1 个答案:

答案 0 :(得分:0)

如果您不打算完全重新加载整个页面,则应查找如何以Django(即this previous answer中)的形式处理AJAX表单。 否则,您可以按照以下步骤更改views.py代码:

def home_view(request,*args,**kwargs):
    api_key = "RGAPI-9b573263-7b5a-433e-9e82-a973f5db4749"
    name = ""
    tier = ""
    rank = ""
    lp = 0

    if request.method == 'GET':
        form = NameForm(auto_id='myform')
        return render(request,"home.html",{'form' : form, 'showdiv': False})

    if request.method == 'POST':
        form = NameForm(request.POST)

        if form.is_valid():
            summoner = form.cleaned_data["summoner"]
            region = form.cleaned_data["region"]
            url = "https://{}.api.riotgames.com/lol/summoner/v4/summoners/by-name/{}?api_key={}".format(region, summoner, api_key)

            response = requests.get(url).json()
            id = response["id"]
            name, tier, rank, lp = ranklookup(id, region, api_key)
            return render(request, "home.html", {
                'form': form,
                'rank': rank,
                'tier': tier,
                'lp': lp,
                'name' : name,
                'showdiv': True })

和模板(现在完全不使用javascript):

{% extends 'base.html' %}

{% block content %}
<h2> League of Legends Rank lookup</h2> <br>

<div id ="ranklookup"> 
    <form id="{{ form.auto_id }}"  method="post">
        {% csrf_token %}
        {{ form }}
    </form>  

    <button type="submit" id="but" form="{{ form.auto_id }}" value="button">
        Submit</button><br><br>

{% if showdiv %}
    <div id="showRank">
        Name: {{ name }}<br>
        Rank: {{ tier }}{{ rank }}<br>
        LP: {{ lp }};
    </div>
{% endif %}

{% endblock %}