尝试在urlpattern

时间:2016-10-22 23:52:22

标签: python django django-views django-urls

所以我的目标是在urls.py中填充关键字<category>以制作动态网址格式。当我点击BoxesView中的帖子时,我的urlpattern仍然是http://127.0.0.1:8000/1/1/而不是http://127.0.0.1:8000/news/1/,就像我想要的那样。

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

在我的模板中也有这个:

<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>关键字工作正常。

1 个答案:

答案 0 :(得分:0)

选择应该是这样的。

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