What's the best way to "embed" a page number in a URL? - django

I'm developing a blog application using Django. Currently, the URL /blog/ displays the front page of the blog (the first five posts). Visitors can then browse or "page through" the blog entries. This portion is mapped to /blog/browse/{page}/, where page, of course, is an integer that specifies which "page" of blog entries should be displayed.
It's occurred to me, though, that perhaps the "page number" should be an attribute of the querystring instead (e.g., /blog/browse/?page=2), since the content of the browse pages is not static (i.e., as soon as I add another post, /blog/browse/2/ will have different contents than it had before the post was added). This seems to be the way sites like Stack Overflow and Reddit do things. For example, when paging through questions on Stack Overflow, a "page" attribute is used; likewise, Reddit uses a "count" attribute.
Extending this thinking, I realize that I use the same template to render the contents of both /blog/ and /blog/browse/, so it might even make sense to just use a URL like /blog/?page=2 to page through the contents of the blog.
Any suggestions? Is there a "standard" way of doing this, or at least a "best practice" method to use?

For my money, the best general purpose approach to this issue is to use the django-pagination utility. It's incredibly easy to use and your URLs should have the format you desire.

I prefer to use the GET URL parameter, as in URL?pg=#. It's very common and provides a standard visual clue to users about what is going on. If, for instance, I want to bookmark one of those pages or make an external link, I know without thinking that I can drop the pg parameter to point at the "latest" front-page index. With an embedded #, this isn't as obvious... do I leave off the parameter? Do I always have to set it to 1? Is it a different base URL entirely? To me, having pagination through the GET parameter makes for a slightly more sensible URL, since there's an acceptable default if the parameter is omitted and the parameter doesn't affect the base URL.
Also, while I can't prove it, it gives me the warm fuzzy feeling that Google has a better chance at figuring out the nature of that page's content (i.e. that it is a paginated index into further data, and will potentially update frequently) versus a page # embedded inside the URL, which will be more opaque.
That said, I'd say this is 99% personal preference and I highly doubt there's any real functional difference, so go with whatever is easier for and fits in better with your current way of doing things.
EDIT: Forgot to mention that my opinion is Django specific... I have a few Django apps so I'm relatively familiar with the way they build their URLs, and I still use a "pg" GET parameter with those apps rather than embedding it in the URL directly.

It seems like there are two things going on. A static page, that won't change and can be used for permalinking, like an article, as well as a dynamic page that will update frequently. There is no reason you cannot use both. URL rewriting should allow this to work quite nicely. There's no reason to let the implementation control the interface, there is always at least one way to skin every cat.

Related

Simple static breadcrumb in Django

How to create something like this:
If user is in:
http://127.0.0.1:8000/about/ then in my base.html I have:
You are here: <li>Home</li>
Etc.
Is there a simple way?
This can get tricky, depending on what you mean by "breadcrumbs".
Django's URL routing system has no inherent hierarchy since any URL can map to any view.
So the "hierarchy" has to be completely specified by you.
…and passed by you to the template in either your view, or in a context processor.
You'll want to assign both a URL AND a name for the URL (so you know /about/ is "Home").
There are a bajillion ways to do this, and it all sort of depends on how flexible you want it, how complicated your URL patterns get, whether you want to support nesting, etc.
Normally, I just use Django Breadcrumbs. This project handles all of the weirdness of breadcrumbs, has a very easy to use API, and handles even weird cases.
While a full code sample would probably be helpful, it's a long and thorny problem, so you're better off reading the documentation for django-breadcrumbs, and then returning here with questions.

Need help regarding design of Django urls and views

Apologies if this has been discussed before, have searched and searched but didn't find anything useful :)
But here goes.
We're currently in the process of rewriting a portion of our webapp. Our app is rather old and therefore suffers from some rather cowboy'ish approaches to programming, conventions and urls.
What we're looking for is a simple clean way to design our views and urls so that we can maintain both easier in the future.
The problem is; as of now our urls.py file for the main site is one big mess. a lot of urls that point to a unique view that only does one thin.
Ex. list_books/, edit_book/ etc.
when it comes to specific formats etc. we have something like list_books_json/
(these aren't the actual urls though, but just used to prove a point since the real urls are much worse)
What we want to do now is clean it up a bit. And we we're wondering what the best way to get around it would be??
What we have thought of so far(after reading a lot of things on the subject):
We've thought of designing our urls after the following pattern:
domain/object/action/
so the urls for the apps "staff" site for changing books in the app would be:
staff/books - to view all books (GET)
staff/books/ID - to view one books (GET)
staff/books/new - to create a new book (POST)
staff/books/ID/edit - to edit specific books (POST)
staff/books/ID/delete - to delete specific books (POST)
The thought was then to have only 1 view, views.staff_books() to handle all these actions when dealing with books through the "staff" part of the site.
so that staff_books() checks for ID or a certain "action" (edit, new, delete etc.)
The result would be fewer, but a lot larger views that have to handle all aspects of staff/books. Right now we have a ton of small views that handle only one thing.
Does this makes sense, can you see potential problems? How do you guys go about it??
One place where I think we're lost is in regards to formats.
Where would you put ex. the request for returning the response in json?
we're wondering "staff/books.json" or "staff/books/ID.json" etc. and then keeping all the json logic in the same "staff_books()" view.
So thats it basically. I'm sorry the question is a little "fluffy"... We basically need some examples or good design advice as to how to structure urls and views.
Kind Regards
pete
As an extension (and solution) to your problem I would suggest to use the strategy pattern. Since you already have a structure and the only thing that differs is "how" it is supposed to be carried out, this pattern fits your problem perfectly. What I mean by that is the following:
Create a view which is your entry point to your application with functions named as your url-based functionality (edit, new, delete etc.). I.e where your url.py determines where to go from there.
Create classes which do your stuff based on your domains etc. Lets call them Book, Calendar etc for now.
Implement functionality of those classes, like edit, new, delete etc.
in your view then, determine what class to instantiate and call the corresponding function, e.g in View.edit() call domain.edit()
I think that should do it ^^
Hope it helps :D

Django - URL design and best practices for identify one object

Im actually working in a django project and I'm not sure about the best format of the URL to access into one particular object page.
I was thinking about these alternatives:
1) Using the autoincremental ID => .com/object/15
This is the simplest and well known way of do that. "id_object" is the autoincremental ID generated by the database engine while saving the object. The problem I find in this way is that the URLs are simple iterable. So we can make an simple script and visit all the pages by incrementing the ID in the URL. Maybe a security problem.
2) Using a <hash_id> => .com/object/c30204225d8311e185c3002219f52617
The "hash_id" should be some alphanumeric string value, generated for example with uuid functions. Its a good idea because it is not iterable. But generate "random" uniques IDs may cause some problems.
3) Using a Slug => .com/object/some-slug-generated-with-the-object
Django comes with a "slug" field for models, and it can be used to identify an object in the URL. The problem I find in this case is that the slug may change in the time, generating broken URLs. If some search engine like Google had indexed this broken URL, users may be guided to "not found" pages and our page rank can decrease. Freezing the Slug can be a solution. I mean, save the slug only on "Add" action, and not in the "Update" one. But the slug can now represent something old or incorrect.
All the options have advantages and disadvantages. May be using some combination of them can some the problems.
What do you think about that?
I think the best option is this:
.com/object/AUTOINCREMENT_ID/SLUG_FIELD
Why?
First reason: the AUTOINCREMENT_ID is simple for the users to identify an object. For example, in an ecommerce site, If the user want to visit several times the page (becouse he's not sure of buying the product) he will recognize the URL.
Second reason: The slug field will prevent the problem of someone iterating over the webpage and will make the URL more clear to people.
This .com/object/10/ford-munstang-2010 is clearer than .com/object/c30204225d8311e185c3002219f52617
IDs are not strictly "iterable". Things get deleted, added back, etc. Over time, there's very rarely a straight linear progression of IDs from 1-1000. From a security perspective, it doesn't really matter. If views need to be protected for some reason, you use logins and only show what each user is allowed to see to each user.
There's upsides and downsides with every approach, but I find slugs to be the best option overall. They're descriptive, they help users know where there at and at a glance enable them to tell where they're going when they click a URL. And, the downsides (404s if slugs change) can be mitigated by 1) don't change slugs, ever 2) set up proper redirects when a slug does need to change for some reason. Django even has a redirects framework baked-in to make that even easier.
The idea of combine an id and a slug is just crazy from where I'm sitting. You still rely on either the id or the slug part of the URL, so it's inherently no different that using one or the other exclusively. Or, you rely on both and compound your problems and introduce additional points of failure. Using both simply provides no meaningful benefit and seems like nothing more than a great way to introduce headaches.
Nobody talked about the UUID field (django model field reference page) which can be a good implementation of the "hash id". I think you can have an url like:
.com/object/UUID/slug
It prevents from showing an order in the URL if this order is not relevant.
Other alternatives could be:
.com/object/yyyy-mm-dd/ID/slug
.com/object/kind/ID/slug
depending of the relevant information you want to have in the url

How can you tell if a site has been made with Django?

A company I'm looking at claims to have made the website for an airline and a furniture store using Django, but when I look at the sites, there is no indication what the underlying web technology is. How can you tell?
This is quite an old question, but I don't see any canonical answers. As the other answers have noted though, there's no sure-fire way to know, and if someone wanted to hide the fact that they're using Django, they can. That said, you can always do a little detective-work and determine with some confidence whether it uses Django or not. If that's your goal, here are some strong indicators you can look out for:
Admin Panel
First and foremost, check if the site has a /admin/ page. If it does, and it gives that familiar Django admin login page, you're 99% sure (unless someone went through a lot of trouble to make it look like Django).
Forms
There are a number of things you can look out for in forms:
Form fields with id attributes starting with id_
Check for a hidden field with the name csrfmiddlewaretoken
If the site has a formset, check for -TOTAL-FORMS and -DELETE hidden inputs.
Cookies
If the site uses the contrib.auth package for authentication, you will probably see a cookie called sessionid being set when you log in.
Forms will also probably set a cookie called csrftoken.
Trailing Slashes
Trailing slashes after URLs, and/or redirecting you to the page with a trailing slash if you try to go to one without it. This is Django's default behavior, and to my knowledge not extremely common in other frameworks. Note, though, that it can be easily deactivated in Django.
Error Pages
Failing all this, or still not being convinced, you can try to force error pages, and try to learn something from that. Go to an unmapped URL with a 404 page, and see if DEBUG still happens to be true (in which case you should probably notify the owner that they're not being very secure about their site).
You can try a few things, such as attempting to find error pages, and checking the default location of the administration panel that Django creates, but overall there's no way to determine what technologies a given site is using.
See also: https://stackoverflow.com/questions/563316/is-there-a-generic-way-to-see-what-is-a-website-running-on/563335#563335
Look for the csrf input box. This is present on any forms. But this can be turned off though not very recommended. Also if it's an old version of django this may not exist. But if it's there it's a strong indicator.
This is present on any page that have a post form. And it looks like this:
<input type='hidden' name='csrfmiddlewaretoken' value='3b3975ab79cec7ac3a2b9adaccff7572' />
Navigate to a page with a formset, and check if there are *-TOTAL_FORMS or *-DELETE hidden inputs.
That doesn't prove that they are using Django, but might be a clue that they are (with the mentioned model formsets).
Try to navigate to some 404 error page, or something of that sort. Chances are slim, but try to find a default django error page.
You can also try to login to www.website.com/admin and see if you get the default django admin page.
Other than that, if that didn't work, then you just can't.
There are no reliable indicators to my knowledge but you could check the /admin/ URL to see if you get the standard admin app or sometimes the feed-URLs use a common prefix compared to a common suffix (although this might not be an indicator at all but just a preference of the developers).
Trying to trigger a debug page (either via a 404 or using some broken input that might case an internal error) might also be a good way (although this acts more as a test of competency of the original developers and admin than anything else :-) )
Could you ask the airline and / or the furniture store? I'm guessing that you want to know if this company has good experience in django, I think it is reasonable to ask for references if you are considering working with them.
The other companies may be quite happy to discuss what technologies were used - some are and some aren't, but it's worth asking.

How to get page parent when using Django flatpages?

Since Django urls are arbitrary, including those set when you create flatpages. How can you figure out what a page's parent is? That is if I create a page /about/contact/, then when I am on the contact page (in the template), how can I figure out what the parent page is?
Is there a standard way to do this? Or do I just split the slug on the slashes and use the first section?
Basically I'm trying to figure out how to create different site sections.
As far as I know, django doesn't have a native concept of sections and, as you said, the URLs are arbitrary (they're left to the programmer to decide). If you stick with the same URL structure throughout your whole site (/<section>/page) then you can infer the section from the URL.
I'd rather set the section in the url patterns and pass it to the views (as described in here) which in turn can pass it to the templates...
flatpages are essentially the same thing as static html pages, stored in your database with a pretty admin in front of it.
so just hard code a link, it shouldn't be a big deal.
if it is a big deal, that means flatpages probably isn't the solution for you