arena view

The arena view accepts the request object and then instantiates an ArenaForm object to gather the data needed to respond to the request. A query of the Arenas model objects and its values_list method creates a Python list that contains tuples with the ID and name of every arenaThe request method (either GET or POST) is used in a conditional to determine the appropriate response.

If a GET request is received (that is, the web page is first opened), a random arena object is generated and passed to the template, which shows the arena on the included map. To get a random arena, we use the list of arena names and IDs (values). Once the list is generated, a list comprehension is used to generate a new list containing arena names. 

Using the random module and the # of names in the list (length) generates a random index that is used to select an arena name from the list. This name is then passed to the queryarena function, which populates the form with the arena name, location, and the popup

These values are returned to the browser using the render function. This function is used to pass forms to templates along with the request, and knows where the templates folder is located inside the Arenas application:

@require_http_methods(["GET", "POST"])
def arena(request):
values = Arenas.objects.values_list('id','name1')
if request.method=="GET":
form= ArenaForm(request.GET)
names = [name for id, name in values]
length = len(names)
selectname = names[random.randint(0, length-1)]
form.name, form.latitude, form.longitude, form.popup = queryarena(selectname)
return render(request, "arena/index.html", {"form":form})
else:
form= ArenaForm(request.POST)
if form.is_valid():
selectid = int(request.POST['selections'])
selectname = [name for ids, name in values if ids == selectid][0]
form.name, form.latitude, form.longitude, form.popup =
queryarena(selectname)
return render(request, "arena/index.html", {"form":form})

If a POST request is received (that is, an arena was selected), an ArenaForm class is called by passing the POST data to the class, and the form is validated. The ID of the selected arena is used as a conditional in a list comprehension, allowing us to retrieve the name of the arena. The name is then passed to queryarena, and the details of its location are queried and added to the form before it is returned using render.

The views are complete and the script can be saved. The next step is to run the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset