Django URL Design
I often find myself falling into a world in which I am not so sure about the URLs that I came up with. I think that's mainly because I have a few questions r开发者_运维技巧egarding URL design in django that remain unanswered.
Say, I have built a public profile page for my site users. It can be accessed by providing an user id. Should the user id be part of the URL (ie. /profile/<userid>/
) or should it be provided in the querystring (/profile?userid=<userid>
)? And why?
I use AJAX extensively in my project. Should the AJAX URLs be designed differently from their counterparts? Is there a design pattern for this purpose?
There isn't any hard-and-fast rule here. I'd say that anything which is reasonably static should use the /profile/<userid>/
format. GET parameters - ?userid=<userid>
- should be reserved for things that are more dynamic, are just difficult to encode as part of the URL (such as a set of search terms), or when you need several parameters at once and can't count on the order.
Django discourages the use of query strings and encourages the use of pretty URLs. You just have to set them up properly in your URLconf
. If you haven't read the Django Book (available freely online), you should. It talks about this in chapter 3:
A Word About Pretty URLs
If you’re experienced in another Web development platform, such as PHP or Java, you may be thinking, “Hey, let’s use a query string parameter!” — something like
/time/plus?hours=3
, in which the hours would be designated by the hours parameter in the URL’s query string (the part after the ?).You can do that with Django (and we’ll tell you how in Chapter 7), but one of Django’s core philosophies is that URLs should be beautiful. The URL
/time/plus/3/
is far cleaner, simpler, more readable, easier to recite to somebody aloud and … just plain prettier than its query string counterpart. Pretty URLs are a characteristic of a quality Web application.Django’s URLconf system encourages pretty URLs by making it easier to use pretty URLs than not to.
This chapter details how and why to do this!
I had the same doubt some time ago, and the project leader of my company said me:
"Try to avoid infinite amount of differents URLs"
So, if some parameter can generate infinite differents URLs, it should be send as a parameter (like this: .com?param=), for example a timestamp. There is infinite amount of differents timestamps, so it should be a paramenter.
In the other hand there are values that are bounded, for example one object ID. If you put and ID in the URL, in the worst case you can generate the same amounts of URLs than IDs, but not infinite URLs. In this case the ID can be included in the URL (like this: .com/content//view)
This simple phrase helped me a lot, I hope you too =)
精彩评论