context KeyError in django templateTag - python

My app's templatetag code is throwing a KeyError for a missing key (page) in the context variable. In my template, I do not refer to context variables with context.variableKeyName, I just refer to variableKeyName (e.g. {% if is_paginated %}). And in my template, I can refer to the key page without any exceptions.
How should I get the context with the keys it needs into my templatetag?
Here are the details:
I am using django-profiles to return a list of some profiles:
url(r'^profiles/$', 'profiles.views.profile_list',
kwargs={ 'paginate_by':10 },
name='profiles_profile_detail'),
which calls this bit of code here:
https://bitbucket.org/ubernostrum/django-profiles..
In my template, I test {% if is_paginated %} before I call a templatetag:
{% if is_paginated %}{% load paginator %}{% paginator 3 %}{% endif %}
( I am using a templatetag inspired from http://www.tummy.com/.../django-pagination/ updated for django 1.3 http://djangosnippets.org/snippets/2680/ )
But this leads to the KeyError for 'paged'.

The documentation (comments in the class) of http://djangosnippets.org/snippets/2680/ says:
Required context variables: paged: The Paginator.page() instance.
It is also used in the template tag:
paged = context['paged']
You need to provide this context variable for this template tag to work. I think your best bet is to copy the code of profiles.views.profile_list view and add this context variable. It's unfortunately still a function-based view - otherwise extending it would have been a lot cleanier and easier.

the right way to code is:
{% paginator v 3 %}
v - variable that contains the db items

Related

Variable context between two blocks in Django templates?

I have two blocks that call the same method with same variables. I want to call the method only once, but the result is then outsite the scope of the block tags. I've tried calling this method in the parent template header.html and with a with tag, but nothing seems to work.
This is the layout:
{% extends "header.html" %}
{% load navigation_tags %}
{% block header %}
{% get_section site=site as section %}
{% include "foobar.html" with section=section %}
{% endblock header %}
{% block navigation %}
<nav>
<div class="container">
{% get_section site=site as section %}
{% navigation section.slug %}
</div>
</nav>
{% endblock navigation %}
navigation_tags.py
#register.assignment_tag
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
As mentioned by 2pacho in another answer and Fernando Cezar in a comment, the easiest way to share values between different sections is to set it in the template context. If you are using the render shortcut function, you can pass a dict as the context parameter to add a value to the rendering context of the template. That would be a good place to add it and this would be the easiest place to put it.
return render(request, 'template.html', {'section': get_parent_section(site)})
However, if for some reason, you can't include it in the context, you can use a decorator to add memoization to your function, so that it will cache the computation results and return it immediately when called with the same parameters. You can use functools.lru_cache to do so, or it's Django backport at django.utils.lru_cache.lru_cache if you are using Python 2.x.
#register.assignment_tag
#functools.lru_cache()
def get_parent_section(site):
if site.id == settings.FOOBAR_SITE_ID:
section = Section.objects.get(id=settings.FOOBAR_SECTION_ID)
else:
# This is also a section instance.
return site.default_section
I wouldn't call a method outside .py . Think that this is using Jinja2 templates,
it's powerful but not in the way that the backend can be.
What I recommend you doing in this case is to generate a context for the template and use this variables there.
Would be as simple as adding it to your context where it's being generated.
context['site_parent'] = get_parent_section(site)
Think that Jinja2 (html) has to be as simple as possible and that can help you with basic coding and time saving (like loops to print the exact same information or show and hide code depending on the context) but I would keep it as simple you can when rendering.
If you would like you can read official django website about templates https://docs.djangoproject.com/en/2.0/topics/templates/
But from my expirience I would keep the method calls in the views.py

Wagtail blocks: accessing context and request in overridden get_context

I trying to get the page and the request from context to be able to use pagination inside the block. The only context i get is
context {'self': None, 'value': None}
Is it even possible to have pagination inside a streamfield block?
class CustomStaticBlock(blocks.StaticBlock):
def get_context(self, value):
context = super(CustomStaticBlock, self).get_context(value)
Rendering with
{% include_block block%}
It's now working (within get_context). If someone has the same issue with a StreamField, make sure to render it as:
{% for block in page.body %}
{% include_block block %}
{% endfor %}
The following won't work (empty parent_context):
{% include_block page.body %}
{{ page.body|safe }}
The context from the outer page is available within the block template, but unfortunately not within the get_context method. (This is due to the way the template context is built up - the result of get_context is merged into the parent context.) This is a known limitation:
https://github.com/wagtail/wagtail/pull/2786#issuecomment-230416360
https://github.com/wagtail/wagtail/issues/2824
A possible workaround would be to override the render method (which is admittedly not ideal, because you'd have to repeat some or all of the existing render logic there).

Django get current view in template

How can I get the full name of the current view (my_app.views.index) in a template in Django 1.5?
With forms, I have an object called "view" in the template which I read using a template tag.
But with DetailViews I doesn't see anything similar.
Is there a way using a custom template processor?
Thanks
EDIT
Situation 1:
I retrieve a page, for example '/foo/bar/5/edit'.
Django will call 'foo.views.editbar' with pk=5.
This view renders an template 'foo/bar_form.html'
Situation 2:
If I retrieve '/foo/bar/new'
Django will call 'foo.views.newbar'
This view renders the same template as above ('foo/bar_form.html')
How can I check in this template 'foo/bar_form.html', from which view it has been rendered?
The result should be one of
'foo.views.editbar'
'foo.views.newbar'
Type just in view
{% with request.resolver_match.view_name as view_name %}
...
{{ view_name }}
...
{% endwith %}
I'm not sure I completely understand the requirement, but take a look at inspect.stack.
inspect.stack()[1][3]
Just set attribute to request object in view:
setattr(request, 'view', 'app.views.func')
and check this in template:
{% if request.view == 'app.views.func' %}
do something
{% endif %}
It worked for me.

I have problems with setting up django-pagination

I'm making a template for Django site (it's quote database). I wanna have Digg-like pagination. Altough, author of the application has made his own pagination, unfortunately without page numering (just "previous" and "next" links). So I've installed django-pagination, but I can't use it with the site. I'm completly new in Django, even programming - I'm just a simple webdesigner... OK, here we go.
There is the original script: https://bitbucket.org/fleg/fqdb/
The first thing is a problem with template context processors. My settings.py didn't have this section, so I added it exactly like in django-pagination documentation. When I run the site, I get an error: "Put 'django.contrib.auth.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application". So how I have to order that?
A second problem is template. I use it exactly like on the screencast:
{% extends "fqdb/base.html" %}
{% load pagination_tags %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
{% if quotes %}
{% autopaginate quotes %}
{% for quote in quotes %}
{% include 'fqdb/quote_body.html' %}
{% endfor %}
{% paginate %}
{% else %}
<p>Brak cytatów.</p>
{% endif %}
{% endblock %}
But I get "Template error: Caught KeyError while rendering: request". But... Seriously, I don't know what's wrong with this code!
There is the paginated view - quote list. It work without pagination, so I don't think if it's a problem, but maybe.
def list_paged(request, page, order_by_what, title, reverse_name):
hash = get_ip_hash(request)
lista = Quote.objects.filter(accepted = True).order_by(order_by_what)[:]
returnDict = {'quotes': lista, 'title': title, 'hash': hash, 'sidebar': get_sidebar()}
return render_to_response('fqdb/quote_list.html', {'quotes': get_quotes(quotes)}, context_instance=RequestContext(request))
I have modified it to not paginating, because it's django-pagination task. You can find original view on Bitbucket.
Maybe do you know some better pagination solutions?
It looks like you need to add django.contrib.auth.context_processors.auth and django.core.context_processors.request context processors to your TEMPLATE_CONTEXT_PROCESSORS setting.
Before you defined TEMPLATE_CONTEXT_PROCESSORS, django would have used the default. It looks as if some of your code requires the auth processor, hence your first error message.
The KeyError looks to me as if you require the request processor.
Try the following in your settings file:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
#"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
#"django.core.context_processors.static",
#"django.contrib.messages.context_processors.messages")
"django.core.context_processors.request"
)
I've used the default list given in the Django 1.3 request context docs, added the request processor, and commented out the ones that you don't seem to need.
The order of template context processors does not usually matter, as long as they do not define overlapping variable names.
If the objects are passed from a templatetag
def comment_app(context):
objects = Comments.objects.get_tree_for_object(context['content_object'])
return {
'comments_tree': objects,
'request': context['request']
}
register.inclusion_tag('comments/comment_app.html', takes_context=True)(comment_app)
note the: 'request': context['request']
{% autopaginate quotes N%}
N - how many items you need for each page

Possible to limit filters ManyToMany/Foreign Key in Django admin for a model where the relationship is defined on the other model?

So the title is a bit obtuse, I know, but I couldn't think of a more succinct way to state it. Here's the issue:
I've created two proxy models for "user types", both inheriting from django.contrib.auth.User. Each has a custom manager limiting the queryset to items belonging to a particular Group. Specifically, there's a PressUser which is any user belonging to the "Press" group and StaffUser which is any user in any other group than "Press".
The issue is that when I add 'groups' to list_filters on my StaffUsers modeladmin, the resulting filter options are every group available, including "Press", and not just groups available to StaffUsers.
I've research a bit online and came up with a custom filterspec that should produce the behavior I want, but the problem is that the User model's 'groups' attribute is actually a related_name applied from the Group model. As a result, I can't attach my filterspec to 'groups' in my proxy model.
Is there any other way to apply the filterspec? Alternatively, is there a better approach to filtering the items returned by the default filterspec?
So, I was able to solve my own problem. For those that might run into a similar situation, here are the steps:
The approach I took is to modify the change_list.html template and manually filter out the items I didn't want to be included. There's quite a number of changes to make, though.
First, add a changelist_view method to your ModelAdmin:
# myproject/account/admin.py
class StaffUserAdmin(models.ModelAdmin):
...
def changelist_view(self, request, extra_context=None):
groups = Group.objects.exclude(name__in=['Press',]).values_list('name')
extra_context = {
'groups': [x[0] for x in groups],
}
return super(StaffUserAdmin, self).changelist_view(request,
extra_context=extra_context)
Basically, all we're doing here is passing in the filtered list of Groups we want to use into the context for the template.
Second, create a change_list.html template for your app.
# myproject/templates/admin/auth/staffuser/change_list.html
{% extends "admin/change_list.html" %}
{% load admin_list %}
{% load i18n %}
{% load account_admin %}
{% block filters %}
{% if cl.has_filters %}
<div id="changelist-filter">
<h2>{% trans 'Filter' %}</h2>
{% for spec in cl.filter_specs %}
{% ifequal spec.title 'group' %}
{% admin_list_group_filter cl spec groups %}
{% else %}
{% admin_list_filter cl spec %}
{% endifequal %}
{% endfor %}
</div>
{% endif %}
{% endblock filters %}
This one deserves a little explanation. First, the template tag loads: admin_list is used for the default Django template tag responsible for rendering the filters, admin_list_filter, i18n is used for trans, and account_admin is for my custom template tag (discussed in a sec), admin_list_group_filter.
The variable spec.title holds the title of the field that's being filtered on. Since I'm trying to alter how the Groups filter is displayed, I'm checking if it equals 'groups'. If it does, then I use my custom template tag, otherwise, it falls back to the default Django template tag.
Third, we create the template tag. I basically just copied the default Django template tag and made the necessary modifications.
# myproject/account/templatetags/account_admin.py
from django.template import Library
register = Library()
def admin_list_group_filter(cl, spec, groups):
return {'title': spec.title, 'choices' : list(spec.choices(cl)), 'groups': groups }
admin_list_group_filter = register.inclusion_tag('admin/auth/group_filter.html')(admin_list_group_filter)
The only things that I've changed here are adding a new argument to the method called 'groups' so I can pass in my filtered list of groups from before, as well as adding a new key to the dictionary to pass that list into the context for the template tag. I've also changed the template the tag uses to a new one that we're about to create now.
Fourth, create the template for the template tag.
# myproject/templates/admin/auth/group_filter.html
{% load i18n %}
<h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul>
{% for choice in choices %}
{% if choice.display in groups %}
<li{% if choice.selected %} class="selected"{% endif %}>
{{ choice.display }}</li>
{% endif %}
{% endfor %}
</ul>
No big surprises here. All we're doing is putting all the pieces together. Each choice is a dictionary with all the values needed to construct the filter link. Specifically, choice.display holds the actual name of the instance that will be filtered by. Obviously enough, I've set up a check to see if this value is in my filtered list of groups I want to show, and only render the link if it is.
So, it's a bit involved but works remarkably well. Just like that, you have a list of filters that is exactly what you want instead of the default ones generated by Django.
I'm going to tell you off the bat that I've never done this before myself, so take it with a grain of salt.
What I'd suggest would be to override get_changelist on your ModelAdmin, to return a custom ChangeList class, which you can define somewhere in your admin module.
Your custom ChangeList class would simply override get_filters, so you can map your custom FilterSpec for the group field.
Another thing that might interest you are patches from the feature request ticket for specifying custom filter specs. The latest patch doesn't work for Django 1.3rc1 yet, although #bendavis78 recently posted that he's working on a new one, but depending on your version of Django it may apply cleanly.
It looks like it barely missed the cut to get included into the 1.3 milestone, so I figure it's going to make it into the trunk as soon as work beings on Django 1.4.

Categories