回答編集履歴
1
追加の回答を記述
test
CHANGED
@@ -17,3 +17,89 @@
|
|
17
17
|
# snip
|
18
18
|
|
19
19
|
```
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
カテゴリとブログを表示したいのであれば、下記のようにすれば表示されると思います。
|
24
|
+
|
25
|
+
アクセスするURLは、`http://127.0.0.1:8000/blog/categories/`です。
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
```python
|
30
|
+
|
31
|
+
# blog/models.py
|
32
|
+
|
33
|
+
class Blog(models.Model):
|
34
|
+
|
35
|
+
category = models.ForeignKey(Category, verbose_name='カテゴリ',on_delete=models.PROTECT
|
36
|
+
|
37
|
+
related_name='blogs')
|
38
|
+
|
39
|
+
# snip
|
40
|
+
|
41
|
+
|
42
|
+
|
43
|
+
# blog/views.py
|
44
|
+
|
45
|
+
from django.views import generic
|
46
|
+
|
47
|
+
from .models import Category
|
48
|
+
|
49
|
+
class CategoryListView(generic.ListView):
|
50
|
+
|
51
|
+
model = Category
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
# blog/urls.py
|
56
|
+
|
57
|
+
from .views import CategoryListView
|
58
|
+
|
59
|
+
urlpatterns = [
|
60
|
+
|
61
|
+
path('categories/', CategoryListView.as_view(), name='category-list'),
|
62
|
+
|
63
|
+
]
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
# <project_name>/urls.py
|
68
|
+
|
69
|
+
urlpatterns = [
|
70
|
+
|
71
|
+
path('blog/', include('blog.urls')),
|
72
|
+
|
73
|
+
]
|
74
|
+
|
75
|
+
```
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
```html
|
80
|
+
|
81
|
+
<!- blog/templates/blog/category_list.html -->
|
82
|
+
|
83
|
+
<html><head></head>
|
84
|
+
|
85
|
+
<body>
|
86
|
+
|
87
|
+
{% for category in object_list %}
|
88
|
+
|
89
|
+
<p>Category: {{ category.name }}</p>
|
90
|
+
|
91
|
+
{% for blog in category.blogs.all() %}
|
92
|
+
|
93
|
+
<p>Blog: {{ blog.title }} </p>
|
94
|
+
|
95
|
+
{% endfor %}
|
96
|
+
|
97
|
+
<br />
|
98
|
+
|
99
|
+
{% endfor %}
|
100
|
+
|
101
|
+
</body>
|
102
|
+
|
103
|
+
</html>
|
104
|
+
|
105
|
+
```
|