How can I pass a variable to all the HttpResponse? - django

I am learning Django and I want to list in all my pages the categories, that are for example categories = Category.objects.all(), but I think it's very redundant to declare that variable in all my views and pass it in every HttpResponse. Is there any way to do it for all?

If you want to add categories to all the pages it may be useful to write a custom template tag, https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

Related

Dynamic name variable on django template

I'm having a problem with django. I have a dict with all my site texts for translations. For example:
term = {"level_1": "Noob",
"level_2": "Noob 2"}
The problem is, how can I access this key on django template?
I have
img src="/images/level_{{player.level.id}}.jpg"
title="{{term.level??????? }}"
I tried:
title="{{term.level{{player.level.id}}}}
but of course this didn't work.
Django's template language is (by design) pretty dumb/restricted. In his comment, Davind Wolever points at Accessing a dict by variable in Django templates?, where an answer suggests to make a custom template tag.
I think that in your case, it is best to handle it in your view code. Instead of only passing along a player into your context, pass both the level ID and the level name.
Possibly you can even directly pass the image url and the level name? Not constructing the URL in your template makes it more readable.

Accessing global variable in view using context processor in Django

Assuming I have a context processor:
def title(request):
return {'titles': 'mytitle'}
I can access this variable in template as {{ titles }}.
But how can I do so in a view?
def myview(request):
print request.titles
doesn't seem to work - 'WSGIRequest' object has no attribute 'titles'
Or maybe there is a better approach (than context processors) to have global variables accessible in both views and templates?
Thanks in advance.
Add your context processor method path (folder.context_processor.application_context) to TEMPLATE_CONTEXT_PROCESSORS.
in my case application_context is the method which i defined inside file context_processor.py
and method "application_context" returns {'titles': 'mytitle'}
if you want to use "title" as global variable in views use it in this way
global_var = RequestContext(request).get("app_config")
titles = global_var.get("titles")
print titles
The only advantage is "Same variable 'titles' will be visible for templates and also in your views"
Context processors aren't in any way global variables. They are simply functions that are run when a RequestContext is initiated, which add items to that context. So they're only available wherever you have a RequestContext, ie in a template.
Your examples don't really give a good idea of what variables you're looking to access. If it's just some constants you want to use everywhere, a good way is to define them somewhere central, say in settings.py, and import that module wherever you need it - plus use a context processor to add them to the context.
If you need the data in your views, it's cleaner to use Middleware in conjunction with a Context Processor:
Create a trivial custom middleware to store some data on the request object, say at request.x (example). Now you can access this in your views directly.
Enable django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS to have request.x accessible from your templates.
See my related question: Django: How to provide context to all views (not templates)?

Database localization in Django

I am using .mo files for localization in Django.
Also, in my database, I store some translated text in different fields, such as:
name_en, name_es, name_de (they are all columns in each row).
What will be the best method to choose the correct field inside a template?
i.e.:
{{ name.some_method }} will generate the correct translation based on the current localization.
Thanks,
Meit
You should look at http://goodcode.io/articles/django-multilanguage/ Here’s a simple solution that may fit your use case and is easy to implement and understand.
You should look at Django Transmeta, it work the same way as what you've done (DB fields with language code) but it's a more complete solution. It already deal with the template stuff, etc.
You can check Model Internationalization and Django Packages for more info and ideas in this domain.
I can see two method for doing this, one in your view and the other one is in the template...
In view:
Probably you keep the user language information somewhere so,
user_lang = 'es'
obj = Somemodel.objects.get(pk=123434)
obj.local_name = getattr(obj, 'name_%s'%user_lang)
So, you keep local translation in a specific variable of the instance and in your template you can use is as:
{{obj.local_name}}
But that might be costly if you wish to pass the template a queryset instead of a single instance. For a such usege you have to evaluate that value for each object in your queryset.
In template:
That is a more complex way of solving the porblem in the template...
Define a template tag and pass object_id, and local language information and get the translated text using a similar getattr function. But in that point, if you wish to use this for more than one model, you probably have to pass a content type information for your template tag too, such as:
{% get_translation <object_id> <content_type_id> <local_language> %}
And in your template tag function, do something like:
from django.contrib.contenttypes.models import ContentType
....
cont_obj = Content_type.objects.get_for_id(<cotent_type_id>) #get the related model
obj = cont_obj.get_object_for_this_type(pk=<object_id>) # get your object
return getattr(obj, 'name_%s'%<local_language>)

Django: Should I use Query Strings or clean url's to map display parameters? And how?

I have the following urlconf:
urlpatterns = patterns('page.manager.views',
url(r'^$', 'pages', name='page_manager-pages'),
url(r'^add/$', 'add_page', name='page_manager-add_page'),
url(r'^(?P<page_id>\d+)/', include(object_patterns)),
)
The 'pages' view must return an object list of all pages. The user will be offered several display/search options through a side menu:
- created: any/ past 6hours/12hours/24hours/week
- Status: any/ status_1/status_2/status_3
- Duration: any / duration_1/duration_2/duration_3
etc.
These options are used to select which values should be presented to the user and can be used in combination, eg: created=any, status=status_1, duration=duration_1
My question is, how best to achieve this in Django?
What I have so far:
I can subclass a generic view for list objects, creating a view which takes the arguments(created, status, duration, etc) and provides the proper queryset(with the chosen[or default] ordering options passed along with the other arguments).
To pass these arguments, query strings seem to be right for this, since we are selecting from a resource(the list of all pages). Yes/no?
I'm also aware we get this information from request.GET.get('argument_name').
But how to create the links for the search options? eg: any, any/ status_1/status_2/status_3. We need to know which are already active, so...template tag? An easier way perhaps?
Is this the proper solution to handle this type of thing in Django, or is there a better way?
Since you have discrete, optional and unordered pieces of knowledge contributing to your query, I think that GET is the best way. Also, note that request.GET is a dict (ergo, you can do request.GET['status']).
As for the search options, I'd say a template tag and a context variable might either be appropriate depending on the details of your view. My most likely approach is to populate a context dict with True / False flags for which need to be displayed and then have {% if %} blocks to sort it out in the template.

Use url args in views, is it possible?

I'd like to use url arguments in views (not templates, I know how to do that).
So is it possible to use them like:
def item_link(self, item):
return mainpage_url_name + "%s/%i" % (item.slug, item.cid)
mainpage_url_name - is of course defined in url patterns (as name variable)
I'm a total newb in Django...
Thanks
First you should use names for your url patterns as documented here.
Then you can use reverse() to use these names in your views or methods.
Following your comments you are using the syndication framework.
Therefore you should make sure that you define get_absolute_url() for you models, ideally using the permalink decorator (for a clean reversing of your urls).
Looking at the example from Django's docs that should be all that's necessary.
To specify the contents of <link>, you
have two options. For each item in
items(), Django first tries calling
the item_link() method on the Feed
class. In a similar way to the title
and description, it is passed it a
single parameter, item. If that method
doesn't exist, Django tries executing
a get_absolute_url() method on that
object.