How do I generate standardized model instance template code in django? - 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.

Related

If I have a field in a base template in Sitecore, can I vary its Title depending on which page template is inheriting it?

In Sitecore, I have a field which is re-used by several page templates. I use basepage inheritance, partly so I don't have to configure the source, help-text and so on each time it is used.
However there are times when the field has a slightly different meaning for one particular page template, and I would like to adjust the Title and help text accordingly to make it easier for the content editors.
Can anyone suggest a good way of doing this in Sitecore? Or is the solution just to make another copy of the field and edit that accordingly, especially as that's only a few seconds work.
Update: Thanks for the answers, I agree with all of them. The difference in the purpose of the fields was so subtle that I didn't think it warranted different fields, but I guess that's a kind of micro-optimisation that will just end up confusing everyone anyway, and certainly isn't worth developing a whole UI / datastore just for this purpose.
Good question, and one that most Sitecore people arrive at eventually. That fact is that the help text is part of the field item. So if you want different help text, you need a different field.
As you point out, the fields sometimes have a different meaning. This is an indicator that it should in fact be a different field.
My suspicion is that you're probably better defining the field more than once.
It may well be possible to modify how Sitecore generates the editing controls shown in Content Editor so that your field's title varies. But that implies you need to store some configuration somewhere to say "when should it change" and "what should it change to". And that's likely to take some time to set up. Plus I think that might be confusing to future developers on the project as it's unexpected behaviour for a field to change it's appearance in different places?
So I'd argue that multiple definitions of the field will be easier for other developers to understand, and probably less prone to mistakes.
If this is not a field that is different on every page, I would keep the inherited field, whether or not it is used by the current page, and create a new one to suit the changed purpose. If the field does have a different meaning on every page, then I would remove it from the base template and re-make it for each page template.
If you have this field on your base page template and it is used on most pages, you will want to ensure that you are still able to use it on the other pages that need it, even if there are one or two exceptions where it does not apply. However, if the purpose of this field changes on every page, then it is better architecture to create a separate field on each page.
It is best practice to use each field for a defined, uniform job; you should not be re-purposing fields between items, as it will lead to confusion for both developers and content editors.
Depending on how many templates you have it may be worth taking that field out of the base template and create two separate templates for these fields.
Essentially will probably have the same field name but with a different help text and title.
Then just inherit the one you want.
This way you keep it separate and this makes better sense being separated as mentioned above.
If you have loads of template already using it then maybe a quick script to swap these over before applying the new template to help change existing ones over (only if you have lots of templates using this base template already)
Hopefully I've made sense here.
As everyone has stated, you need different field for different page templates.
I would do the following, create a new template which contains your common field, and make page templates that use this field with same 'meaning' inherits the new template.
And for page templates that use this field with different meaning, add a separate field to each template.

Fetch data from DB on every pageload

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.

Django - Single model instance

I want to add a layout model to my website (a general settings file), and I want it to be available in the admin interface for configuration.
class Layout(...Model):
primary_header
logo_image
...
This structure shouldn't saved be in a table.
I am wondering if there is a built-in feature that can help me do this.
Thanks
My use case is a configurable layout of the website. Wordpress style. I would like to store that data in a concrete class, without having to implement the file /xml serialization myself.
What about an abstract model? It does not save in the database and is meant to be subclassed, but you are allowed to create instances of it and use its attributes. I assume you want some kind of temporary data structure to pass around that meets the requirements of a model instance.
class Layout(models.Model):
class Meta:
abstract = True
If you for some reason need actual concrete models, and are fine with it creating tables for them, you could technically also re-implement the save() method and make it no-op.
I don't really understand where and how you will be using this, but this is indeed a model that doesn't save.
Personally, I have actually used models that aren't intended to be saved, in a project that uses mongodb and the nonrel django fork. I create models that are purely meant to be embedded into other models as nested sub-documents and I never want them to be committed to a separate collection.
Update
Here is another suggestion that might make things a whole lot easier for your goal. Why not just use a normal django model, save it to the database like normal, and create a simple import/export function to save it out to XML or read into an instance from XML. That way you get 100% normal admin functionality, you can still query the database for the values, and the XML part is just a simple add-on. You can also use this to version up preferences and mark a certain one as active.

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.