尝试在 urlpattern 中填充 <keyword>

Trying to populate <keyword> in urlpattern

所以我的目标是在 urls.py 中填充关键字 <category> 以制作动态 url 模式。当我在 BoxesView 中单击 post 时,我的 url 模式仍然是 http://127.0.0.1:8000/1/1/ 而不是我想要的 http://127.0.0.1:8000/news/1/

造成我大部分问题的原因是 django 强迫我为我的 CATEGORY_CHOICES 使用元组,而不是列表。出于某种原因,它只允许在我的参数中使用数字(例如“1”、“2”),而不是 'news'、'sport' 等,所以在我的 article 函数中views.py、name 必须是数字,无论数字是在元组括号的第一部分还是第二部分。

我的模板中也有这个:

<a href="{% url 'article' category=post.category id=post.id %}">

由于我上面提到的问题,post.category这里永远是数字而不是单词。我认为我在 (?P<category>\w+).

中混淆了我的类别关键字

这是我的代码:

choices.py

CATEGORY_CHOICES = (
('news', '1'),
('sport', '2'),
('technology', '3'),
('science', '4'),
('cars', '5')

)

urls.py

BV = BoxesView.as_view()

urlpatterns = [
url(r'^news/', BV, name='news'),
url(r'^sport/', BV, name='sport'),
url(r'^technology/', BV, name='technology'),
url(r'^science/', BV, name='science'),
url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'),
]

views.py

class BoxesView(ListView):
template_name = 'polls.html'

def get_queryset(self):
    for a, b in CATEGORY_CHOICES:
        name = resolve(self.request.path_info).url_name
        if a == name:
            category = b
            print(category) # '1', '2' etc
            queryset_list = Post.objects.all().filter(category=category).order_by('-date')
        return queryset_list


def article(request, id, category):
name = resolve(request.path).kwargs['category']
for a, b in CATEGORY_CHOICES:
    if b == name:
        name = b
        print(name) # '1', '2' etc
instance = get_object_or_404(Post, id=id, category=name)

queryset = Post.objects.all()
context = {
    'object_list': queryset,
    'instance': instance
}
return render(request, 'article.html', context)

template.html

<a href="{% url 'article' category=post.category id=post.id %}">

models.py

class Post(models.Model):
category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')

def __str__(self):
    return self.title

def get_absolute_url(self):
    return '/%s/%s/' % (self.get_category_display, self.id)

所以我仍然不确定我必须做什么才能使 urlpattern 关键字 <category> 起作用。 (顺便说一下,<id> 关键字工作正常。

选择应该是这样的

CATEGORY_CHOICES = (
    ('1','news'),
    ('2','sport'),
    ('3','technology'),
    ('4','science'),
    ('5','cars'), )