models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class ArticleTag(models.Model):
caption = models.CharField(max_length=12)
def __unicode__(self):
return self.caption
class Article(models.Model):
title = models.CharField(max_length=32, unique=True)
content = models.TextField()
author = models.CharField(max_length=32)
cate_types = (
(1, 'smartArticle'),
(2, 'urlArticle'),
(3, 'farmArticle'),
(4, 'cookerArticle'),
)
category = models.IntegerField(choices=cate_types)
article_tag = models.ForeignKey(ArticleTag)
def __unicode__(self):
return self.title
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
#注意这里<...>中的命名
url(r'^article-(?P<category>\d+)-(?P<article_tag_id>\d+).html', views.article, name='article'),
]
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from app01 import models
# Create your views here.
def article(request, *args, **kwargs):
# print kwargs
condition = {}
for k, v in kwargs.items():
kwargs[k] = int(v)
if v == '0':
pass
else:
condition[k] = v
print condition
articles = models.Article.objects.filter(**condition)
#注意存内存中的输出到模板这样。。
cate_types_list = models.Article.cate_types
article_tags = models.ArticleTag.objects.all()
return render(request, 'article.html', {'articles': articles, 'article_tags': article_tags, 'cate_types': cate_types_list, 'kwargs': kwargs})
template-article.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.cc a{
display: inline-block;
border: double 2px;
margin: 10px;
}
.active{
background-color: aqua;
}
</style>
</head>
<body>
<div class="cc">
{% if kwargs.article_tag_id == 0 %}
<a class="active" href="/article-{{ kwargs.category }}-0.html">全部</a>
{% else %}
<a href="/article-{{ kwargs.category }}-0.html">全部</a>
{% endif %}
{% for tag in article_tags %}
{% if kwargs.article_tag_id == tag.id %}
<a class="active" href="/article-{{ kwargs.category }}-{{ tag.id }}.html">{{ tag }}</a>
{% else %}
<a href="/article-{{ kwargs.category }}-{{ tag.id }}.html">{{ tag }}</a>
{% endif %}
{% endfor %}
<br>
{% if kwargs.category == 0 %}
<a class="active" href="/article-0-{{ kwargs.article_tag_id }}.html">全部</a>
{% else %}
<a href="/article-0-{{ kwargs.article_tag_id }}.html">全部</a>
{% endif %}
<!-- 注意下面写法,c.0-->
{% for c in cate_types %}
{% if kwargs.category == c.0 %}
<a class="active" href="/article-{{ c.0 }}-{{ kwargs.article_tag_id }}.html">{{ c.1 }}</a>
{% else %}
<a href="/article-{{ c.0 }}-{{ kwargs.article_tag_id }}.html">{{ c.1 }}</a>
{% endif %}
{% endfor %}
{% for article in articles %}
<h2>{{ article.title }}</h2>
<span>{{ article.author }} ---{{ article.article_tag }} ---{{ article.get_category_display }}</span> <!-- 这里注意, 在模板打印存在内存的标签写法-->
<p>{{ article.content }}</p>
{% endfor %}
</div>
</body>
</html>
网友评论