I installed Django template pagination tag from: https://github.com/jmcclell/django-bootstrap-pagination and while I followed all the instructions, I'm getting 'source' errors.
Apparently I'm doing something wrong.
===========================================
EDIT 3
SETTINGS.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.request",
)
VIEW.py:
def pagination(request):
location = Location.objects.all()
return render_to_response('pagination.html',
location,
context_instance=RequestContext(request))
TEMPLATE
{% load bootstrap_pagination %}
<h1>Location</h1>
{% for location in location %}
<h2>{{ location.name }}</h2>
{% endfor %}
{% bootstrap_paginate location %}
ERROR:
AttributeError at /pagination/
'str' object has no attribute 'paginator'
Request Method: GET
Request URL: http://127.0.0.1:8000/pagination/
Django Version: 1.5.4
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'paginator'
Error during template rendering
In template /home/jr/Documents/python/amapp/sdr/article/templates/pagination.html, error at line 7
'str' object has no attribute 'paginator'
1 {% load bootstrap_pagination %}
2
3
4
5
6
7 {% bootstrap_paginate location %}
I'm the author of the library, but you must forgive me as I haven't used Python in quite some time and I've core dumped most of my knowledge about this library.
So, #WayBehind was correct, your first mistake was using "page_obj". That was simply an example. In your case, you want to use "location"
However, you never got to see that error because you have a more pressing error which is that the library isn't playing nice with your setup. I wrote this library with Python 2.7 with the request context preprocessor. Please double check that you have the context preprocessor enabled as per the documentation and please be sure you are using Python <3.0. I know for a fact the library does not currently working on 3.x. There is a fork of the library where some other folks have been working to fix that and I am actively keeping an eye on it to pull those changes in when ready, but as of now it just doesn't work.
If you are using Python 2.x and you have the request context preprocessor enabled, I am not sure why you would be getting that error. If you can confirm those two things are true, I'll be happy to take a closer look tomorrow.
Edit:
This may or may not be an issue, but I notice that you loop through your Location object using the same variable name for the instance:
{% for location in location %}
<h2>{{ location.name }}</h2>
{% endfor %}
{% bootstrap_paginate location %}
Is it possible that Django's template scoping is such that the object you are passing to bootstra_paginate is the last instance of "location" rather than the entire set? This is an off the cuff guess as a first stab at this because otherwise things appear to be correct.
Have you followed all the steps ?
Request is in the context_processor (settings.py)?
TEMPLATE_CONTEXT_PROCESSORS = (
....
"django.core.context_processors.request",
....
)
You are using obj_list in the template, but do you have anything inside obj_list ? Maybe you have to use "location" instead of "obj_list" ? Because I think your object list is inside location (Location objects) but you are using obj_list like in the example. In the example obj_list is just a variable example for an object list.
EDIT:
Change this:
def pagination(request):
args = {}
args.update(csrf(request))
args['location'] = Location.objects.all()
return render_to_response('pagination.html', args)
for this:
from django.template import RequestContext
def pagination(request):
location = Location.objects.all()
return render_to_response('pagination.html', 'location':location,context_instance=RequestContext(request))
Using page_obj worked for me, for anyone wondering why this doesn't work when using Django 2.0.2 and django-bootstrap4 0.0.6.
I came across this by digging through the context variables in the error message that showed up from Django's DEBUG mode.
Related
I'm working in a Flask app, and I'm trying to set it up to create dynamic webpages based on the data in the SQL database. For example, if we scrape data about a certain criminal, I want Flask to route my requests such that I can type:
myflaskapp.com/criminal/[criminal's name]/
and be taken to a page specifically for that criminal. This is the relevant portion of the views.py that I've already written:
#app.route('/criminal/<first_name>')
def criminal(first_name):
criminal = Individual_Criminal.query.filter_by(first_name=first_name).first()
return render_template('user.html',
criminal=criminal)
Now, when I call the Individual_Criminal.query.filter_by(first_name=first_name).first() in a Python shell, it returns as expected:
However, when I set up my Flask server, and do (what I believe to be) the exact same command query, it just gives me a blank page (with my navbar and stuff extended from the base html.)
The HTML for the page I'm trying to call is simple:
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<h1>{{ criminal.full_name }}</h1>
<hr>
{% endblock %}
As you can see, it should be returning the particular criminal's full name (in this case, Bryan Sanford). Instead, it returns this:
Instead of the requested criminal's full name, the way that the HTML specifies.
Where am I going wrong here? My thinking is that if I can do that exact query that's in my views.py file and have it return the correct value, it should work the same in my Flask app. However, clearly there are some wires crossed somewhere. Can any of you wonderful people help me untangle this?
edit: as discussed in one of the answers comments, when I change views.py to include print(criminal.first_name), it fails, throwing AttributeError: 'NoneType' object has no attribute 'first_name'. Even though the exact same line works exactly as expected in the actual database!
Your routing seems to be wrong?
This is not the same
myflaskapp.com/[criminal's name]/
as
#app.route('/criminal/<first_name>')
Try
myflaskapp.com/criminal/[criminal's name]/
Situation
I'm writing a checker program that checks Django templates. For example I want to check if all Django templates that use url template tag, use it with quotes on first parameter so that it is Django 1.5 compatible. Also I want to check that they have included {% load url from future %} in their templates.
For example if my program parses the following Django template, I want it to raise an exception.
{% extends 'base.html' %}
<td>
<a href="{% url first second %}">
</a>
</td>
But this template should get parsed without exception.
{% extends 'base.html' %}
{% load url from future %}
<td>
<a href="{% url 'first' second %}">
</a>
</td>
I'm not limited to this simple example. I have other parsings to do. For example I want to check how many load template tags are present in the template.
Question
How can I elegantly solve this parsing problem?
I don't want to use regular expressions.
I this Django it self has some utilities in this regard. I think using them is a good idea, but I don't know how.
I want to run the program separately from Django. So I don't want Django to run the program itself (with render_to_response). (This is important)
Code
Please show me some code that can solve the example I mentioned. I want to detect whether {% load url from future %} is in the code. Also I want to check every url template tag and check if the first argument is quoted.
Bonus:
I want to be able to see the rendered HTML that Django generates from this template, and do my HTML parsing on it. (for example with PyQuery)
You say...
I want to check if all Django templates that use url
template tag, use it with quotes on first parameter so that it is
Django 1.5 compatible.
...and...
I don't want to use regular expressions.
...because...
the result of that might become a huge spaghetti code
...but, frankly, writing a parser from scratch is likely to be even messier than using a regular expression. I don't see what's so messy about a regex as simple as something like...
"{% *url +[^']"
...and I doubt there's a non-regex-based solution that's as terse as that.
With regards to...
Also I want to check that they have included
{% load url from future %} in their templates.
If your intention is to ensure Django 1.5 compatibility, this is pointless. According to the Django 1.5 release notes, the new-style url tag syntax is enabled by default, so the line {% load url from future %} won't have any effect.
And in versions prior to 1.5, it's much simpler just to put...
import django.template
django.template.add_to_builtins('django.templatetags.future')
...at the bottom of your settings.py and be done with it. :-)
You can also use the compile_string method.
>>> from django.template.base import *
>>> settings.configure()
>>> compile_string("<a href='ab'></a>{% cycle 'row1' 'row2' as rowcolors %}", None)
>>> [<Text Node: '<a href='ab'></a>'>, <django.template.defaulttags.CycleNode object at 0x10511b210>]
The compile string method is utilized by the Template class and is the method used to produce the node list.
Tested in Django 1.8 Alpha.
https://github.com/django/django/blob/1f8bb95cc2286a882e0f7a4692f77b285d811d11/django/template/base.py
Next code still uses django, but it can check if syntax is correct:
>>> from django.template import Template
>>> from django.template.defaulttags import URLNode
>>> t = Template("{% load url from future %}\n{% url projects_list company.slug %}")
>>> for node in t.nodelist:
... if isinstance(node, URLNode):
... for arg in node.args: print(arg)
...
company.slug
>>> t2 = Template('{% load url from future %}\n{% url "projects_list" company.slug }')
>>> for node in t2.nodelist:
... print(node)
...
<django.template.defaulttags.LoadNode object at 0x32145d0>
<Text Node: '
{% url "projects_list" c'>
>>>
As you see last node is not URLNode
This is my previous post. Template includes and django views/urls. How (do/should) they work? .
Again, the mini box works fine. I've taken the advice given and trying to work with it.
So I have a profile(request, profile_type, username) view. I'm trying to grab the 'profile_intros'context from that and place it into the included mini_profile.html template.
I've tried making an inclusion tag(as I will be needing it elsewhere throughout the site):
#register.inclusion_tag('includes/profile_info.html', takes_context=True)(profile_info)
def profile_info(context):
profile_intros = FundRecommendation.objects.filter(investor=profile).count()
return{
'profile_intros' : context['profile_intros'],
}
and throwing {% profile_info %} into the included mini_profile.html template. I've followed the django doc example and I really don't know what I'm doing wrong.
I'm getting :
Exception Type: TemplateSyntaxError
Exception Value: Invalid block tag: 'profile_info'
You forgot to use {% load ... %} to load the template tag library.
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty.
Example:
apps/someapp/views.py:
def_context_var('app_name', 'Calendar')
templates/base.html:
{% if app_name %}You are in {{ app_name }} app.{% endif %}
....
{% if app_name %}Subsections of {{ app_name }}: ...{% endif %}
I considered the following:
Declare a variable in the app (in a view, or in URLs), and make a context processor. But I can't understang how to extract that var given the request object.
Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code.
#1 but nicer: make methods (like in the example above) that are executed on server restart, write the data into a dict, then a context processor somehow (how?) gets the application name and extracts the data from the dict. Where do I put the method, the dict, how does the context processor know where the view object is in?
You can call resolve(request.path) in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name.
I learned how to authenticate users in Django months ago, but I've since upgraded and am having some problems so it occurred to me this morning that I may not have been doing it correctly from the start so I decided to ask.
In my project's urls.py file I've got ^accounts/login/$ and ^accounts/logout/$ both wired up to the built-in login() and logout() views (at django.contrib.auth.views) and ^accounts/profile/$ is connected to a view I've written, called "start_here" whose contents are basically this:
def start_here(request):
if request.user:
user_obj = request.user
else:
user_obj = None
is_auth = False
if request.user.is_authenticated():
is_auth = True
return render_to_response("profile.html", {'auth': is_auth,'user': user_obj,})
Now, "profile.html" extends a master template, called master.html, inside which is a "navbar" block whose contents are supposed to change if 'auth' == True (snippet below)
{% block navbar %}
{% if auth %}
Link A
Link B
Link C
Link D
Link E
Link F
Logout
{% else %}
Login
{% endif %}
{% endblock %}
My problem is that when I log in, and it redirects to /accounts/profile, the navbar doesn't display Links A-F + Logout, it displays only "login". It doesn't work the way I expect it to unless I manually copy-paste the above block into profile.html. When calling render_to_response(), does the context I provide get passed to the parent template as well as the child?
Full source to master and profile.html: http://dpaste.com/hold/128784/
I don't see anything suspect in the code.
This answer is tangential, but Jim's suggestion to use RequestContext is so good I want to explicitly explain how to do it.
You can reduce your start_here function to
from django.template import RequestContext
def start_here(request):
return render_to_response("profile.html", {},
context_instance=RequestContext(request))
By using RequestContext, user is automatically added to the context. Instead of using
{% if auth %}
use
{% if user.is_authenticated %}
Yes the context you pass in render_to_response() is passed to the named templates and ALL the templates it includes or inherits from.
You should look into Using RequestContext
Another thing to check...
Just making sure:
your profile template begins with
{% extends 'master.html' %}
In order to make sure django correctly identifies users, you need to make sure it is properly enabled in your settings module. specifically, you need to make sure that the SessionMiddleware and AuthenticationMiddleware modules are enabled in your settings.MIDDLEWARE_CLASSES. also be sure that auth is in your installed apps and you have run syncdb since enabling it.
If you have not taken the above steps, then django will not be able to detect when users have logged in and perform request setup properly.