0

So guys I have 2 problems. I am pretty new in Django and Python. I build a page with a form and I can input data in those fields, I receive the data do some operation with it and pass back other variables which are shown in a div under the form field after a button was clicked. It is actually working but the page refreshes so I can see the result for only one second. Second Problem is that I have to click twice on the button so it shows me the right result. Example: First button click Result shows x, then I use other input and click button, result shows x again. After I click the button again it shows the right result, how do I fix this problem aswell.

And do you have suggestions how to make this system better?

I am already really thankful for your help.

My view file:

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

And my HTML file:

{% 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 %}"
yassoplaya
  • 67
  • 1
  • 3
  • 9
  • You want to look into AJAX. If the data needs to be passed to the template on demand then you will need a view function for it, but you need to stop the default behaviour of the form also triggering a page refresh – roganjosh May 20 '19 at 11:51
  • Yea, I found our that I need to look into AJAX to do that, but can you say how can I fix my second problem? – yassoplaya May 20 '19 at 12:08

1 Answers1

0

If you are not trying to actually reload the page entirely, you should look for how to handle AJAX form in django (i.e. in this previous answer). Otherwise, you can just change your views.py code as follows:

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 })

and the template (which now does not use javascript at all):

{% 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 %}
Filippo Lauria
  • 1,965
  • 14
  • 20
  • Wanted to try this out but got a key error for the line id = response["id"] – yassoplaya May 20 '19 at 12:27
  • Ok got it to work , the url variable was not right the way you made it, used my line and it worked. This is perfect this solves all my problems, thank you Sir. Do you you actually have suggestions how I can make this system better? – yassoplaya May 20 '19 at 12:32
  • whoops.. I forgot some `{}`.. now it should work. I recommend you to always considering the [django documentation](https://docs.djangoproject.com/en/2.2/) as your very first starting point, when using django. – Filippo Lauria May 20 '19 at 12:43