Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lesson 12 - More Model-based Views (cont'd)

Lesson 12 - More Model-based Views (cont'd)

Dana Spiegel

December 05, 2012
Tweet

More Decks by Dana Spiegel

Other Decks in Technology

Transcript

  1. Review: Model-based Views 2 • List of Teams and Players

    • Create templates • Create views • Add views to url router • Including url routers in base url router
  2. Review: Individual Team View • To provide a drill-down view

    into an individual team requires specifying which team to display • Handled by indicating the team ID in the URL • The URL specifies which team is being viewed • URL provides easy and understandable presentation in browser, and is SEO friendly • Links to team view pages are easy to generate • Single URL pattern for team view for any team 3 http://dev.hatcherydevshop.com:8080/softball/team/3/
  3. Review: Team View: Template • Team view template expects a

    team object in the context • Create softball/team/view.html • Present the team name in an H1 at the top of the page • Include a list of players with statistics • Iterate through team.players.all • Create a table with all player data • Include a list of games played • Iterate through team.rosters.all • Store game in template variable • Don’t have roster.game method! • Template requires it, so create it! • Display text in green if team is winner, red if loser • Versus column requires a test to see if team is home or away 4
  4. Review: Team View: View Method • Create team_view method to

    support view.html template • To know what team to display, team_view requires a team_id parameter • Using the team_id parameter, look up team with Team.objects.get • If team lookup fails because team doesn’t exist, return a 404 response using raise Http404 • Include team in template context dictionary 5 def team_view(request, team_id): """ Lists the details of the team with team_id """ try: team = models.Team.objects.get(id=team_id) except models.Team.DoesNotExist: raise Http404 return TemplateResponse(request, 'softball/team/view.html', { 'team': team, 'record': team.record(), })
  5. Review: Team View: URL Routing • To make team_view work,

    need to support url with team ID specified • URL regex must look for digits representing team ID • Once team ID is found, capture in team_id variable • All captured text is passed to view as parameters • Named captures using (?<name>...) will be passed to view based on parameter name (so order isn’t important) • Since view takes a team_id parameter, it will process the passed team_id properly • Because captured text is captured as digits, it will be passed as an int 6 url(r'^team/(?P<team_id>\d+)/$', 'softball.views.team_view', name='team_view')
  6. Add Win/Loss Data to Template • Adding win/loss data presentation

    in template really isn’t easily implemented by pulling data from model • Instead, we gather data in view, and pass data to template in context dictionary • Allows reduction in database load—1 query instead of 2 • Makes template rendering a little faster since 1 fewer database call 7 def team_view(request, team_id): """ Lists all teams in the Database """ try: team = models.Team.objects.get(pk=team_id) except models.Team.DoesNotExist: raise Http404 return TemplateResponse(request, 'softball/team/view.html', { 'team': team, 'record': team.record(), })
  7. Review: Add Win/Loss Data to • To display record, use

    index notation to get data from tuple • Use pluralize template filter to show singular/plural text based on value of record • Pluralize works by rendering “s” if value filtered is 0 or > 1 • Renders nothing when value filtered is 1 • Can take an argument representing the letters to render in the case of pluralization of text, for example “es” • Ensures users read content naturally, and is very easy to integrate into template 8 <div class="well well-small right"> Record<br/> <strong>{{ record.0 }} win{{ record.0|pluralize }} / {{ record.1 }} loss{{ record.1|pluralize:"es" }}</strong> </div>
  8. Redirecting the Root Path • Use a redirect at the

    root path to get people to the right default page • Don’t want to have 2 URLs for a single resource • Django provides a simple redirect view, like direct_to_template, called redirect_to • Takes a url in view dictionary • Automatically redirects browser to redirect url every time url is requested 9 from django.views.generic.simple import redirect_to url(r'^$', redirect_to, { 'url': 'team', }, name='softball_home'),
  9. Adding Links to Other Pages • url template tag makes

    computing urls for other site pages easy • Using page name as specified in urls.py, generate URL for specific pages • Include parameters for URLs that require them • Use url tag in href attributes • Always use url tag instead of hardcoding URL so it is easy to change location of resource without worrying about every template and view that links to it 10 url(r'^team/$', 'softball.views.team_list', name='team_list'), url(r'^team/(?P<team_id>\d+)/$', 'softball.views.team_view', name='team_view'), <a href="{% url team_view team_id=game.away_roster.team.pk %}"> {{ game.away_roster.team.name }}</a>
  10. Adding Bootstrap Base Template • Clone a local copy of

    repo to local machine • Download Bootstrap: http://twitter.github.com/bootstrap/ • Impement base.html • Copy static assets to appropriate directory • Add assets to git • Push them to Github, then pull them to dev server • Implement navigation bar with links to Teams, Players, Games • Make tables look pretty • Implement page scaffolding in base.html and in team and player templates • Add icons for home team and to signify win 11 <tr {% if game.winner == team %}class="text-success"{% else %} class="text-error"{% endif %}> ... " <td>{{ game.away_score }} to {{ game.home_score }} {% if game.winner == team %}<i class="icon-ok"></i>{% endif %}</td> </tr>