Django for-programmers_5

This is based on Day 12.

  1. view-refactoring

get_absolute_url

stores/models.py

from django.core.urlresolvers import reverse
class Store(models.Model):

name = models.CharField(max_length=20)
notes = models.TextField(blank=True, default='')

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('store_detail', kwargs={'pk': self.pk})

stores/templates/store_list.html

<h2><a href="{{ store.get_absolute_url }}">{{ store.name }}</a></h2>

Store Templates

store/views.py

def store_list(request):
# ...
return render(request, 'stores/store_list.html', {'stores': stores})

def store_detail(request, pk):
# ...
return render(request, 'stores/store_detail.html', {'store': store})

Template inheritance

python manage.py startapp base

base/templates/base.html

<!DOCTYPE html>
<html>
<head>
<title>{% block title %}午餐系統{% endblock title %}</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>

<body>
{% block body %}
<nav class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'home' %}">午餐系統</a>
</div>
</div>
</nav>
{% endblock body %}
</body>
</html>

INSTALLED_APPS

INSTALLED_APPS = [
'pages',
'stores',
'base',
# ...
]

pages/templates/pages base.html

{% extends 'base.html' %}

pages/templates/pages/home.html:

{% extends 'pages/base.html' %}

{% block body %}
{{ block.super }}
{% endblock body %}

stores/templates/stores/base.html

{% extends 'base.html' %}

{% block body %}
{{ block.super }}
<div class="container">{% block content %}{% endblock content %}</div>
{% endblock body %}
{# stores/templates/stores/store_list.html #}

{% extends 'stores/base.html' %}

{% block title %}店家列表 | {{ block.super }}{% endblock title %}

{% block content %}
{% for store in stores %}
<div class="store">
<h2><a href="{{ store.get_absolute_url }}">{{ store.name }}</a></h2>
<p>{{ store.notes }}</p>
</div>
{% endfor %}
{% endblock content %}
{# stores/templates/stores/store_detail.html #}

{% extends 'stores/base.html' %}

{% block title %}{{ store.name }} | {{ block.super }}{% endblock title %}

{% block content %}
<h1>{{ store.name }}</h1>
<p>{{ store.notes }}</p>
<table class="table">
<thead>
<tr><th>品項</th><th>單價</th></tr>
</thead>
<tbody>
{% for item in store.menu_items.all %}
<tr><td>{{ item.name }}</td><td>{{ item.price }}</td></tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
{# base/templates/base.html #}

<!-- nav-->
<nav class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'home' %}">午餐系統</a>
</div>
<div>
<ul class="nav navbar-nav">
<li><a href="{% url 'store_list' %}">店家列表</a></li>
</ul>
</div>
</div>
</nav>
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.