Django is rendering template from the database efficient - python

This is not a HOWTO question, as it, as such, has been answered before here
I am trying to integrate Django with modern frontend framework, and I found that it is possible to store and render Django templates from models. Since it is not a standard, I am wondering what are the advantages (or disadvantages if that's the case) of file based templates.
Reading though the documentation, I have seen that it is recommended to actually cache templates and models as much as possible for best performance, so why would it not be recommended to store templates in the database? It seems very convenient to me that in doing so pages can be edited from the admin panel (where you can add a code editor), which, along with the rest framework and a front end framework synergize very well.
From my research, the template tags and template language seem to work and the context can be passed in a view as well. the only thing I cannot figure out is the {include .. } tag, as it does not seem to point to a view. (although a custom tag cam be made to have this function)
Can such a setup be used in production? or are there security/performance/other concerns?

It's not recommended because templates are the developer's responsibility, not the site admin's.
Otherwise, there's not much performance difference between reading files directly from filesystem and from database.
One drawback of this approach is you don't get revision history (using git, mercurial etc). Sure, you can implement something similar to save the revisions in the database, but then why not use the better tools which already exist?
There's a Django flatpages app which lets you save HTML content in database. But the purpose of the app is to allow site admins to edit HTML content, such as information for an "About Us" page, because writing this info is not a developer's responsibility.

Related

How to Replace Entire default Djnago Admin with custom Admin

I want to replace the default Django Admin templates with a completely revamped bootstrap version. The data in the Dashboard should be populated from the DB. How do I work with templated files ? Which files should be overriden ? In which template tag does HTML code go ?
From django docs on admin:
The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.
It's possible to change templates to do what you want, but that will be very complex - you have to basically rewrite most of the templates, get to know how it is working internally and probably change that too to your own design (after all, you are going to show specific details, like charts, data and so).
You will faster to achieve results if you going to build your own app, that will work exactly like you need without multiple fixes. Does it have to use js frameworks depends entirely on your requirements. Usually they are much more simple for admin backends, that are going to be used by owners, not clients. Anyway, if you don't have experience or knowledge in this, you will probably better off with just plain static django templates.
Django admin is just a same app as the ones you build, so limitations will be the same. Security wise, it doesn't offer much that you can't do yourself - make sure you have permissions set in models/views. Read more about security in django.
From functionality point of view, django admin just comes with CRUD access to your models, which can be done quite quickly. Once you past that, you will have much easier time adding functionality to your own app instead of overriding django admin.
Overall, I advise you to build your app for CMS-like admin panel. JS frameworks is neat, but that require burden of multiple additional tests (with api mocks), constant swapping between adding api / writing a component and much higher time consumption overall.

Is it possible to generate static html from Django Cms?

Hi I'm working on a project based on Django Cms
DJango Cms
Most of the templates ara generated via an APi call in ajax.. I wondered if is possible to generate an HTML static file from the original template file in order to avoid dynamic calls.
Short answer: Yes.
Long answer: It depends.
There's little stopping you from just creating static HTML pages (you could for example just use wget to crawl you website. However note that this only works if your content is not dynamic, as in, it doesn't depend on whether a user is logged in or not etc. If you only use plugins that always have the same output, regardless of the request, then it'll work.
Since Django CMS gives you a lot of power to write highly dynamic plugins, there's no built-in way of generating these static pages (the chances of someone using it without realizing the drawbacks are high).

Are there any good options for baking out a Django site as static files?

Say you have an existing database-backed Django site. Something simple, like single model containing a record for every minor league baseball team. The model is accessed by one view that lists all the teams, and another that accepts a slug and then creates a detail page all about that team.
Is there a good option for converting the app into a stack of baked out flat files, so that it could be served from a static file service like Amazon's S3?
I've toyed with Hyde but it's not clear to me how it applies to an existing site backed by a database.
Any advice would be very much appreciated. Thank you in advance.
django-medusa is largely unmaintained. These are some alternatives mentioned in the project's README:
django-bakery, built and maintained the lovely people at the Los Angeles Times Data Desk. (Read about it
here.)
The alsoicode/django-medusa fork, by Brandon
Taylor. Among other things, it's been
kept up to date for newer versions of Django.
django-freeze by Fabio Caccamo.
django-staticgen by Mishbah Razzaque.
I understand your intent, but any decent framework these days offers some sort of caching mecanism that alleviate the pains of dynamic content. With a properly implemented cache, the difference between static and dynamic will be trivial. Trust me.
Happy coding, friend.
A new one has just been announced, though it has existed and been used by its author for quite some time:
django-medusa.
I haven't tried using it yet, but it sure looks good: I will be!
I have a similar setup using Django but on GAE. I have created a build script which I use to build my static HTML files. Since GAE's version of Django templates is slightly different, this might need some testing.
But essentially you do something like
from django.template import Template, Context
from django.template.loader import get_template
t = get_template('template1.html') #Need to verify this. GAE template allows me to just call template.render(path, context). Not sure about pure Django templates
c = Context({ 'variable' : 'value'})
with open("file1.html", "w") as f:
f.write(t.render(c)) #This works for me, but if this doesn't in pure Django, try render_to_string
HTH
You are asking for a dynamic site to host in a static environment, that is impossible. The only way is to export all the files, put them into a static server. You can do it with wget, it will copy all the files and convert them to html.
One fallback of this problem is, it can only create html files, if there are links to the pages, ie. search forms etc. will not work, Javascript based linking may not work.
I'm not familiar with anything that will convert an existing django site to a static html site. It might be worth looking at the suite of new django/python PaaS providers. A site like this should be easy to get running on one of these platforms and it should be pretty cheap month to month.
Some providers you might want to checkout include:
Gondor.io
ep.io
Django Zoom

customizing Django look and feel in Python

I am learning Django and got it to work with wsgi. I'm following the tutorial here:
http://docs.djangoproject.com/en/1.1/intro/tutorial01/
My question is: how can I customize the look and feel of Django? Is there a repository of templates that "look good", kind of like there are for Wordpress, that I can start from? I find the tutorial counterintuitive in that it goes immediately toward customizing the admin page of Django, rather than the main pages visible to users of the site. Is there an example of a "typical" Django site, with a decent template, that I can look at and built on/modify? The polls application is again not very representative since it's so specialized.
any references on this would be greatly appreciated. thanks.
Search for generic CSS/HTML templates, and add in the Django template language where you need it. Because unless you are trying to skin a particular app (such as the admin system), there is nothing Django-specific about any of your HTML.
The fact that you're thinking in terms of Wordpress templates, and that you think the tutorial's poll application is highly specialised, are hints that you haven't really grasped what Django is. It isn't a content management system or a blog engine, although it can be used to build those things.
There's no such thing as a typical Django site, and it simply doesn't make sense to have pre-packaged templates, because the front end could be absolutely anything at all - like a poll.
You write the template like you would write any standalone HTML+CSS page, perhaps with placeholders for the content, then turn those placeholders into actual Django template tags. If you know how to do write HTML, then you know how to make a Django template.
Actually Django does not have a "look and feel". You are probably referring to the built in Django Admin application. That app comes with its own templates.
There are third party applications that can change the Admin interface, Django Grapelli is a great example.
For any other application you want to build yourself, or download. Most likely you'll have to do the templates yourself. In order to come up with something pretty you need to learn about CSS/HTML/JS and design principles as the Django Templates will quite likely be out of your way.
I always recommend HTML Dog for learning the basics of HTML, CSS and JS.

What to do after starting simple_server?

For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.
How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.
My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.
Thanks for the help.
EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.
The other answers give good recommendations for what you probably want to do towards your "eventual goal", but, if you first want to persist with wsgiref.simple_server for an instructive while, you can do that too. WSGI is the crucial "glue" between web servers (not just the simple one in wsgiref of course -- real ones, too, such as Apache or Nginx [both with respective modules called mod_wsgi] as well as, for example, Google App Engine -- that one offers WSGI, too, as its fundamental API) and web applications (and frameworks that make it easier to write such applications).
Everybody's recommending various frameworks to you, but understanding WSGI can't hurt (since it will underlie whatever framework you eventually choose). And for the purpose of such understanding wsgiref.simple_server will serve you for a while longer, if you wish.
Essentially, what you want to do is write a WSGI app -- a function or class that takes two parameters (an "enviroment" dictionary, and a "start response" callable that it must call back with status and headers before returning the response's body). Your "WSGI app" can open your index.py or whatever else it wants to prep the status, headers and body it returns.
There's much more to WSGI (the middleware concept is particularly powerful), though of course you don't have to understand it very deeply -- only as deeply as you care to! See wsgi.org for tutorials &c. Gardner's two-part article, I think, is especially interesting.
Once (and if that's your choice) you understand WSGI, you can better decide whether you want it all hidden in a higher level framework such as Django (so you can focus on application-level issues instead) or use a very light and modular toolbox of WSGI utilities such as Werkzeug -- or anything in-between!-)
I would recommend Django.
"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."
Not true with Python. Python is just a language, not an Apache plug-in like PHP.
Generally, you can use something like mod_wsgi to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python language.
You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.]
PHP parses the request and allows you to embed code in the resulting page.
Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps.
Parsing the URL and locating an appropriate piece of code.
Running the code to get a result data objects.
Interpolating the resulting data objects into HTML templates.
"My goal is to begin building simple web applications into my pre-existing static XHTML pages."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Transform your XTHML pages into Django templates. Pull out the dynamic content and put in {{ somevariable }} markers. Depending on what the dynamic content is, this can be simple or rather complex.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered.
"write a basic message board in Python."
Let's look at how you'd do this in Django.
Create a Django project.
Create a Django app.
Define your data model in models.py
Write unit tests in tests.py. Test your model's methods to be sure they all work properly.
Play with the built-in admin pages.
Create Django templates.
Define URL to View function mappings in your urls.py file.
Define view functions in your views.py file. These view functions create the dynamic content that goes in the template, and which template to render.
Take a look at CherryPy. It's a nice http framework.
It depends on what you want to achieve,
a) do you want to just write a web application without worrying too much abt what goes in the background, how request are being handled, or templates being rendered than go for a goo webframework, there are many choices simple http server is NOT one of them. e.g. use django, turbogears, webpy, cheerpy, pylons etc etc
see http://wiki.python.org/moin/WebFrameworks for full list
b) if you want to develope a simple web framework from start so that you understand internals and improve you knowledge of python, then I will suggest use simple http server
see
how can you create a URL scheme so that URLs are dispatched to correct python function,
see how can you render a html
template e.g. containing place
holder variables $title etc which
you can convert to string using
string.Template
b) would be difficult but interesting exercise to do, a) will get you started and you may be writing web apps in couple of days

Categories