I want to check the useragent using Django inside my template. I know this is possible using JavaScript, but I wanted a server side solution.
I know I can use HttpRequest.META in some middleware class, which I am not currently looking for. I want to determine this using some code in the template itself, without any dependency on other files / classes.
Can anybody help?
You need to use context processors, more specifically django.core.context_processors.request.
This SO answer covers it quiet well:
How can I pass data to any template from any view in Django?
Especially this blog post, that is referenced in the SO answer:
http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/
Related
I am following the documentation and have already created my Permission instances so I can decorate my route functions, however, I have no idea how to hide links in the template. I saw an answer on here that used Roles but is there a way to use Permissions from Flask-Principal instead?
Hiding inaccessible links in Jinja2 templates The question asker's answer here sounds really good but would throw out my Permissions, also I don't really understand what he's doing, only that he doesn't have to re initialize the permissions/roles on the jinja2 template side.
My goal is to understand each flask extension's use as I learn. That's why I want to know if there's a way to do this without having to use Flask-Security or throwing out the Permissions I've already defined with Flask-Principal.
I use Flask-Nav with Flask-Bootstrap for creating navigation bar and I think you should follow its structure in your code as well. There are 2 basic steps:
Define a (multi dimensional) list of navigation links in your app code, where you can use all your Permissions during the process. Pass this filtered list to your template.
In your template loop over the list and generate a nice HTML code from it.
IMHO it is the right way to create a role- or permission-dependant navigation bar, because it separates the HTML-generating code from the "app" code.
I would like to view some user information on over half of my website's views.
This information should contain not only trivial username but also some fields from other tables of my project that are associated with current user.
I would also like to put this information into the template that my current view extends, just to keep it DRY.
I already did some research and coded some templatetags hoping that registering tags would help me achieve this but I have no idea how to get user information when there's no request like in views' functions.
Any tips on how to achieve this will be much appreciated. I just started django yesterday and am still a bit confused by it's philosophy.
You can use a context processor to add data to the template context in a DRY way.
In a nutshell, a context processor is simply a function that accepts a request as its first argument, does some additional processing that you add and augments the context with whatever values you want.
You can query an objects models, add the current datetime...pretty much anything you can do with Python or Django can go into a context processor.
In django, https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships, span relationships provide an easy way in django to do a JOIN. Is there a way in the template to do this (using template tags)?
You could do that, I think, because when you write a custom template tag you can import models and run queries on them just as you can anywhere else. But it violates the separation of business logic and presentation that Django's model-view-controller (or model-view-template) design works hard to preserve. Why not do your query in a view and pass the results to a template via the template's context?
If you are asking whether Django comes with a pre-built way to do this, the answer is no. The people who created Django want you to run queries in your views.
I've been working with django over past couple of months. It seems that if I need some new value in a template, the only way to accomplish that is to pass it through the view function directly or an object that can be somehow used to retrieve that information.
What if I want to "PULL" information from the template? Consider the following scenario. I have a template "template1" associated with Application1. Suppose in one column of this template, I want to import information from second application "Application2". Currently the only way I know is to use the Application1's view functions to pull that info from Application2. For every new application I need to change my Application1's view function. So in case I want to keep adding information from different applications(2,3,4 etc), I would need to keep on changing the view function of Application1. This could get cumbersome.
So what I want is something like Wordpress's widget function or Joomla's module type functionality. Simple plug and play, that can "pull" the information from different sources(apps). Does django have something of this sort built-in?
Ah, you have encountered one of the fundamental differences between Django (and most Python templating frameworks) and WordPress (and most PHP frameworks). PHP has a huge global name space that can be accessed from pretty much any place in the page creation process. Python, on the other hand, does not. Many of us consider this to be a Good ThingĀ®.
However, there are times when you wish you had a few more globals for use in your templates. To accomplish this, what you want is a context processor. This is a routine that returns a dict that is automatically included whenever you use RequestContext() to build your call to your template.
You may also want to look at {% expr ... %}. It allows you to break out of the "chains" of the deliberately weak Django templating engine.
Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!
"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"
Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.
MVC (while a noble aspiration) is implemented as follows:
Data is defined in "models.py" files using the Django ORM models.
urls.py file maps URL to view function. Pick your URL's wisely.
View function does all processing, making use of models and methods in models
Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making
The model is defined for you. Just stick to what Django does naturally and you'll be happy.
Architecturally, you usually have a stack like this.
Apache does two things.
serves static content directly and immediately
hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.
Database used by Django view functions.
The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.
Feel free to read the Django documentation. It's excellent; perhaps the best there is.
first, forget all MVC mantra. it's important to have a good layered structure, but MVC (as defined originally) isn't one, it was a modular structure, where each GUI module is split in these tree submodules. nothing to use on the web here.
in web development, it really pays to have a layered structure, where the most important layer is the storage/modelling one, which came to be called model layer. on top of that, you need a few other layers but they're really not anything like views and controllers in the GUI world.
the Django layers are roughly:
storage/modelling: models.py, obviously. try to put most of the 'working' concepts there. all the relationships, all the operations should be implemented here.
dispatching: mostly in urls.py. here you turn your URL scheme into code paths. think of it like a big switch() statement. try hard to have readable URLs, which map into user intentions. it will help a lot to add new functionality, or new ways to do the same things (like an AJAX UI later).
gathering: mostly the view functions, both yours and the prebuilt generic views. here you simply gather all the from the models to satisfy a user request. in surprisingly many cases, it just have to pick a single model instance, and everything else can be retrieved from relationships. for these URLs, a generic view is enough.
presentation: the templates. if the view gives you the data you need, it's simple enough to turn it into a webpage. it's here where you'll thank that the model classes have good accessors to get any kind of relevant data from any given instance.
To understand django fundementals and the django take on MVC, consult the following:
http://www.djangobook.com/
As a starting point to getting your hands dirty with ...
"...trying to find some comparable data / architectural models"
Here is a quick and dirty way to reverse engineer a database to get a models.py file,
which you can then inspect to see how django would handle it.
1.) get an er diagram that closely matches your target. For example something like this
http://www.databaseanswers.org/data_models/product_catalogs/index.htm
2.) create an sql script from the er diagram and create the database,
I suggest Postgre, as some MySQL
table type will not have forgien key constraints, but in a pinch MySQL or SQLITE
will do
3.) create and configure a django app to use that database. Then run:
python manage.py inspectdb
This will at least give you a models.py file which you can read to see how django attempts
to model it.
Note that the inspect command is intended to be a shortcut for dealing with legacy
database when developing in django, and as such is not perfect. Be sure to read the
following before attempting this:
http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin