Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - Two variables in Django URL

I want a URL something like this:

/(category)/(post-slug)

On the link this is what I have:

{% url blog.category blog.slug %}

and for the url.py:

url(r'^(I DON"T KNOW WHAT TO PUT ON THIS PART TO GET THE CATEGORY)/(?P<slug>[0-9A-Za-z._%+-]+)', views.post, name='post'),

thanks

EDIT: This is what I have now: Still have NoReverseMatch error at /

urls.py

 url(r'^(?P<category>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$', views.post, name='post'),

index.html

<a href="{% url blog.category blog.slug %}">

views.py

def post(request, slug, category):
    try:
        blog = Blog.objects.get(slug=slug)
    except Blog.DoesNotExist:
        raise Http404('This post does not exist')
    return render(request, 'parts/post.html', {
        'blog': blog,
    })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, your URL tag needs the name of the pattern you are reversing as the first argument:

{% url 'post' blog.category blog.slug %}

or if you are using a namespace, something like:

{% url 'blog:post' blog.category blog.slug %}

You haven't shown your views or models, so we can only guess what your URL pattern should be. I'm not sure why you find the category confusing - you just need to choose a name for the group (e.g. category_slug), and the regex for the group (you might be able to use the same one as you use for slug). That would give you:

url(r'^(?P<category_slug>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$'

Note that there should be a dollar on the end of the regex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...