GWT set variable values with Django templates - django

I am using a tree control in my GWT application. The tree has different items based on the user logged in. One way to populate the tree would be to query the server from my GWT code to get a list of tree items. But since the items will always be shown would it not be better to include information regarding them in the page itself? I am looking for views to achieve this. Would it be possible to get a template engine like django to insert these values into GWT string variables at serving time? Then I can use these string variables to populate the tree. Or is there a better way to achieve this?

I answered a very similar question in the GWT group last year, so you might want to take a look there.
The idea, as you said, is to embed this data inside the host page, instead of firing an additional GWT RPC request during the app's initialization. You can:
Embed the data inside a JavaScript variable in your host page, and access it using the Dictionary class
This is a simple solution, especially if your data is serializable as a dictionary of strings. You could use the templating engine of your choice to insert this data in your host page (Django's, Mustache, FreeMarker, JSP...).
Embed a GWT-RPC payload inside your host page, as explained here and there
This is better if you need to serialize a whole object graph (which might be what you want for your Tree widget, depending on its complexity). It's like a standard GWT-RPC request, but instead of sending an HTTP request at startup, the GWT-RPC "response" would have been be embedded inside your host page when you serve it.

Related

Is it (Un)-REST-full to return details when GET-ing the collection?

My question is about designing an endpoint for getting a list of items in a collection. Here my understanding is that a GET on a collection returns a list of the items in that collection, but no details about these.
A list of resource IDs isn't very nice for a human being, so a GUI front-end would then request details of each item in the collection.
If the collection is say the "users" then the GET on the collection just returns a list of user IDs (ALL OF THEM! Paged, I imagine?)
The GUI then requests details for every ID and uses this to populate an interface. For a list you might say, as an example, just show the user's Full name and Email address in this interface, allowing the user to select one to see more details.
Now I'm thinking it would save a lot of back and forward between the client and the API if the "list retrieve" returned a bit more than just the IDs, maybe include ID, full-name and Email address for each item.
Does that break RESTful-ness? Where do you stop with how much detail to return in a single request? Do you allow the client to specify which attributes to include as part of the request?
What about "searching" a collection? Do you allow arguments to be specified on the GET against the collection to "filter" the results?
The API exists to service the needs of the clients. If your clients need the details, you should be returning them.
That said, there's a tradeoff for highly-cacheable items. If the list is not static but the contents are, you might be better served returning the list of links. Then the client makes one call for each element, and they sit in the cache. Later calls for those elements get served by an intermediate cache, either on the client or somewhere between client and server. That would reduce overall bandwith of calls to the list at the cost of a larger absolute number of calls at first.
Another option is to support a query parameter like ?include=id, full-name, email. By default just return the self link, but clients may specify what properties they'd like to have populated in the representations they get back. If you support this query parameter, I would suggest defaulting to returning only the most essential information.
As far as searching the collection, it depends on the nature and complexity of the search. Query parameters are one option. Using POST to a search endpoint and sending up the search criteria in the body is also reasonable, especially if your url might be longer than 2k characters (the default url length limit for some browsers). You can also do saved searches this way - let the POST create a search criteria resource on the server, and let clients GET /widgets?search-criteria=<id>.

How to generate custom unique ID

We are using Sitecore 7.2 with multi-site implementation. The actual data is shared between multisite, hence it's been stored in common Global Item folder.
We are facing a problem generating aunique ID on URL. I had a good search but could not find any solution except to use Sitecore Item ID.
This is what we want:
domain/players/player_id
e.g. domain/players/1234
where 1234 is uniquely generated ID.
Could someone please suggest if this is possible?
Every page that is managed in Sitecore is a Sitecore Item. As such, you should be able to just navigate to the name of the player item. If you were trying to say in your post that player items are stored in globals and not as pages, then you are left with the following options:
Query String: domain/players/player?playerId={ID}
If this is the route that you choose to take then I would suggest using the player item's Sitecore ID for the value of the query string parameter.
If you have other IDs then put the specified ID there, however it would be easiest with Sitecore IDs
What you would then do is get the item with the ID specified in the query string parameter (or get the item with the player ID specified in the query string parameter, depending on which route you take) and display the data for that player on the page
Sitecore.Context.Database.GetItem(Request.QueryString["playerId"])
playerItems.FirstOrDefault(playerItem => playerItem["Player ID"] == Request.QueryString["playerId"])
Note that this assumes that the Player ID is a field, not the Sitecore ID
If it is the Sitecore ID then change the lambda to use playerItem.ID == new ID(Request.QueryString["playerId"]
Regardless of which one you use, I suggest adding null checks to the QueryString getter
Sublayout Parameters
If you use this method, the query string will not change and people will not be able to get to the page from the direct URL
The process is the same as for query strings, except that you are using Sublayout parameters instead
Note that you must set these in a parent sublayout or in Sitecore (which means that you have a separate page for each player - i.e. this would be a bad solution)
Virtual Items
This is really what I think you are looking for
This can be a lot of work if you do it from scratch, or you can use the Wildcard Module
If you do it from scratch, you will need a custom pipeline and/or processor for handling the requests
Good suggestions from Zachary. I will add a couple more:
1) IIS Rewrite Module. If what you are really after is having external URLs look like /domain/players/1234, you could easily accomplish this by forwarding these requests to something like Zachary's option #1. The client sees /domain/players/1234, but it's really handled by a single Sitecore item at /domain/player/player.aspx?playerid=1234. Client doesn't have to know that.
2) Custom ItemResolver pipeline handler. Custom Pipelines may be a bit intimidating at first, but they are actually pretty easy to implement and highly useful. Would be pretty straightforward to add a new one which checked for "players/1234" and set the ContextItem to your player handling page and drop the ID into a session variable or some context variable.

Django API: how to construct URLs, and handle queries?

Forgive this newbie (and possibly subjective - I don't know) question.
I want to add a REST API to my site. For example, I have a URL that is /post/ that shows all posts, and I'd like to give users a way to get all posts back in JSON.
Is is better to:
define a new API URL structure (e.g. /api/rest/post/ to return all posts in JSON)
use the existing URL structure, and allow users simply to append /json/ on the end of each URL to get JSON objects back? (e.g. /post/json/ to return all posts in JSON)
If the latter, then is there a standard way to implement it, in terms of views? Should I simply add an optional json parameter to all my views?
Thank you for your advice.
Take a look at Piston, which is a Django plugin to handle REST APIs.
Listen to the previous commenter's advise. But in particular that's probably better to use new API URL structure (/api/rest/post/ as you've said). Separating totally different kinds of functionality is always good for your project. In other words, you can place your API documentation at /api/docs/, and it will look natural. If you use same URL structure, it will be not so obvious where to place your docs.
The answer is of course also subjective.

Django - Static content display based on URL

I'm working on a Django site with a basic three column design. Left column navigation, center column content and right column URL specific content blocks.
My question is about the best method of controlling the URL specific content blocks in the right column.
I am thinking of something along the lines of the Flatpages app that will make the content available to the template context if the URL matches a pre-determined pattern (perhaps regex?).
Does anyone know if such an app already exists?
If not, I am looking for some advice about the best way to implement it. Particularly in relation to the matching of patterns to the current URL. Is there any good way to re-use parts of the Django URL dispatcher for this use?
Django CMS is a good suggestion, it depends on how deep you want to go. If this is just the beginning of different sorts of dynamic content you want then you should go that way for sure.
A simple one-off solution would be something like this:
You would just need to write a view and add some variables on the end of the URL that would define what showed up there. Depending on how fancy you need to get, you could just create a simple models, and just map the view to the model key
www.example.com/content/sidecontent/jokes/
so if "jokes" was your block of variable sidecontent (one of many in your sides model instances) the urls.py entry for that would be
(r'^content/sidecontent/(?P<side>)/$,sides.views.showsides),
and then in your sides app you have a view with a
def showsides(request, side):
Sides.objects.get(pk=side)
etc...
For something like this I personally would use Django CMS. It's like flatpages on steroids.
Django CMS has a concept of Pages, Templates, and Plugins. Each page has an associated template. Templates have placeholders where you can insert different plugins. Plugins are like mini-applications that can have dynamic model-based content.
Although Django-CMS is an interesting suggestion, there are quite a few projects that do specifically what you've requested - render blocks of content based on a URL. The main one that I know about is django-flatblocks.

Who should format my data for display?

I have a django view, and this view returns a table which is populated asynchronously with an ajax call.
From the design point of view, which one should I follow:
the django view, called via ajax, returns the content of the table as a json response, containing html markups for each cell. The javascript callback handler takes the contents and slaps them untouched into the table cells.
the django view, called via ajax, returns pure data about what should go into the table, again as a json response. The async javascript callback takes the data, formats them with proper markup, and puts it into the table.
In other words, who should have the responsibility for markup formatting of the cell contents? the view or the javascript ?
I would be tempted to say the first, since the view already returns marked up content. If it returns a json containing marked-up content, there's not much difference.
I would like to hear your point of view.
If you're populating the whole table, you can put your table in its own template and return the table's html via ajax/json.
You'll need to edit the original template to include the table template:
{% include "myapp/_table.html" %}
And in the view, return the rendered template as a json variable, which your javascript will substitute in:
return { 'table': render_to_string("myapp/_table.html", context) }
This approach is good where you always want to update the entire table, and the rendering of the table doesn't require the full context. I'm not sure what the performance is like, but it is a clean way of updating part of the page, because you only define your table once.
It depends (as so often).
If the data is requested only here and now, it would be easier and less error prone to just let it render on server-side with the same set of templates that already rendered the standard view.
If you could think of use cases however, where the data would be needed in other places (like auto-complete fields), it would be better to let JavaScript do the job and create a clean, reusable JSON export.
These options add to all the other answers, and finally it's up to you to decide.
In a MVP system such as Django, the View decides what data should be shown, and the Presenter decides how it should be shown. Therefore the JavaScript should do the bulk of the formatting unless it proves intractably difficult to do so.
It is a good to practice Unabstrusive javascript, also called by some people as Hijax
So, you first have a standard page, that presents the table along with the rest of the page, with table in a particular django-template block.
Once you have this, you can include the extends part of the django template within an "if not ajax", so you only get the required table part in the ajax response which you can load in the client to the required div.
It is un-necessary and redundant to maintain the markup twice once at the server and once at the client, in javascript.
hence, I'd prefer the first option, of server redering, and client only loading the rendered html.
I've come across this several times before, and I generally opt for the latter, where the view returns pure JSON.
However, the approach you choose should definitely depend on several factors, one of which is targeted devices (and their CPU/network constraints). Pure JSON will generally result in smaller payloads and so may be optimal for mobile devices.
It may also make sense to expose both HTML and JSON versions of your content. This is especially helpful if you're looking to create a very lightweight API at some point for your site.
Finally, you can use a library such as John Resig's micro-templating or Closure Templates to simplify client-side HTML generation.
I would go with first choice, sine it presents more pros for user: page loads instantly (no wait for async call), no JS required (e.g. for mobile device)