Fetch data from DB on every pageload - django

I basically need to make a DB query on every view within an app, in order to pass some data to my templates. Since views are not classes, but simple functions, I can't have a construct, where I can do the query.
So, structurally speaking, what is the best practice on where to put this kind of logic? I probably could just create a template tag and do the queries there, but it seems like not very well organized to me.

Firstly, views certainly can be classes: Django has offered class based views since version 1.3.
However, the best way to pass data to every template is to use a context processor.

Related

What is the current (as of 1.8) most efficient way to reuse a variable that results in database queries in a Django app?

I know of with, and I know you can write your own template tags for this purpose, altering the context variable. However, given these circumstances:
Cannot alter an application you are reusing, and do not want to "monkeypatch" its views.
You have multiple isolated blocks in a given template, whatever.html, and, say, a blog_post context variable that has a categories member. You reference this 'categories' field multiple times in the template differently, for instance, you only want the first element in one place/block, and then you iterate them all in a different spot in the template.
You want to avoid duplicating queries altogether.
You do not want to enclose everything with a 'with'/'endwith' block.
What would be the most efficient way to go about this?
Well you can write a middleware for the specific view and alter process_template_response context just before it renders. I think that will help.

Django CBV repeating the same query on each page

I am now using Class Based View in my Django application and it helps me a lot to develop faster.
I still have a question about the best way to implement the following:
I have some information in my database I need to always have in almost every template I have (except the template where user is not logged in).
What is the good method to make this using Django ? Is it okay to create a class based view with a custom query in the .get() method?
Thank you :)
There are various different ways to do this.
If you are consistently using class-based views everywhere, you could create a common base class with a custom get_context_data method that adds your specific data to the context dictionary.
But the more usual ways of solving this problem are nothing to do with class-based views, but apply to all sorts of views. They are custom template tags and context processors.
For me, a context processor is probably the best bet: as long as you ensure that your template is rendered with RequestContext (which it will be if you use any view that inherits from TemplateView) then your extra data will always be added to the template context.

How do I generate standardized model instance template code in django?

I'm developing a website in Django where many of the sites' models' instances are presented to the user in a standardized format on many different pages. I'd like to avoid redundancy in the template coding by creating standard model instance template code then just inserting it each page where a model instance needs to be displayed.
What is the best practice for creating standardized instance display code, then adding it into many different pages?
There are several ways of accomplishing this...
One is to use an include tag and pass your object to the template. Another, similar approach is to create a template tag to render the object, which is useful if you need to do some extra processing in Python before doing the rendering.
Yet another way is to add an instance method to your model to render itself to HTML (or some other format), much the same way a form instance has .as_ul or .as_p that you can call in your template where needed.
Neither way is right or wrong, it just depends on what you're most comfortable with stylistically and what's most efficient for your needs.

django: generic views + custom template tags or custom views + generic/normal template tags

This is more of a best-practices question, and given that I'm quite tired it mightn't make much sense.
I've been putting together a blog app as a learning experience and as an actual part of a website I am developing.
I've designed it like most apps so that you can list blog posts by multiple criteria i.e.
/blog/categories/
/blog/authors/
/blog/tags/
/blog/popular/
etc.
On each page above I also want to list how many entries are a part of that criteria
i.e. for "categories", I want /blog/categories/ to list all the different categories, but also mention how many blog posts are in that category, and possibly list those entries.
Django seems to give you lots of ways of doing this, but not much indication on what's best in terms of flexibility, reusability and security.
I've noticed that you can either
A: Use generic/very light views, pass a queryset to the template, and gather any remaining necessary information using custom template tags.
i.e. pass the queryset containing the categories, and for each category use a template tag to fetch the entries for that category
or B: Use custom/heavy views, pass one or more querysets + extra necessary information through the view, and use less template tags to fetch information.
i.e. pass a list of dictionaries that contains the categories + their entries.
The way I see it is that the view is there to take in HTTP requests, gather the required information (specific to what's been requested) and pass the HTTP request and Context to be rendered. Template tags should be used to fetch superflous information that isn't particularly related to the current template, (i.e. get the latest entries in a blog, or the most popular entries, but they can really do whatever you like.)
This lack of definition (or ignorance on my part) is starting to get to me, and I'd like to be consistent in my design and implementation, so any input is welcome!
I'd say that your understanding is quite right. The main method of gathering information and rendering it via a template is always the view. Template tags are there for any extra information and processing you might need to do, perhaps across multiple views, that is not directly related to the view you're rendering.
You shouldn't worry about making your views generic. That's what the built-in generic views are for, after all. Once you need to start stepping outside what they provide, then you should definitely make them specific to your use cases. You might of course find some common functionality that is used in multiple views, in which case you can factor that out into a separate function or even a context processor, but on the whole a view is a standalone bit of code for a particular specific use.

How can I pass a standard, static variable from all views in Django?

I'm working on a blog application, and I want to have a sidebar that includes a list of all the months the blog has been in existence, to provide links to archives pages. Moreover, I'd like to make this automatically update when the month changes, rather than hardcoding it in the template. Of course, as far as I can tell, this means that I'll have to calculate the list of months in every view, and pass it into every template from every view.
I'd like to avoid this, if possible. Is there a way to calculate the list once and automatically apply it to every template, without having to explicitly pass it into the template from every view?
There are a few possible solutions to your problem.
If you really want to have this on every page on your site a context processor is probably your best choice. Context processors are basic way to inject data into all template contexts. Be aware however that the context processor will be called on every request.
An alternative solution would be to create a custom template tag and use it on a shared base template for all of the pages you wish to have your sidebar. Template tags are a bit more complex to create but they are more flexible.
With either solution you should also look at Django's cache framework. The cache framework makes it pretty easy to temporarily store your calculated values for a while to save some work on each request.
You want a template context processor
Django - having middleware communicate with views/templates
http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#id1
Django's template inheritance should cover this. You could create a base template that handles your sidebar functionality. Your other views extend this template.
Template Inheritance:
http://www.djangobook.com/en/1.0/chapter04/#s-template-inheritance
A combination of custom template tags as mentioned previously and template fragment caching should do the trick.