Infinite scroll in django - django

Is it possible to implement facebook style loading of content while scrolling down? I would like to implement it in an ecommerce site. There are a lot of items in each category and the category page becomes too long. I could implement page numbers but my client wants me to implement that facebook type of loading. Is there anything I can use? Rest of the site has already been built.
I did look into django-endless-pagination but was not able to get it to work. Is there any demo of it so that I can look into it?

We used django endless pagination on www.mymommemories.com without too much problem. Because we were using html5media we did have to add a line to run that function with a one second delay. (setTimeOut("html5media()", 1000). Running it without the delay caused problems in some browsers. If your not using html5media, this should not be a concern however.
Core part of the template code.
{% load endless %}
{% paginate memories %}
{% for memory in memories %}
.
.
.
{% endfor %}
{% show_more %}
In the view we have the following to handle the ajax request.
if request.is_ajax():
template = page_template
return render_to_response(template,context,context_instance=RequestContext(request))
The page_template is not the whole page, just the portion related to the "paging".

I thinks the easiest way to do endless pagination is use jQuery (use $.loads).
You even don't need change the back-end code.

http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Perhaps take a look at that?

Related

Using the Django assignment_tag built-in tag the right way

I'm working on a project in Django.
Earlier today, I discovered the new (Django >= 1.4) assignment_tag. I immediately decided that it was just what I needed EVERYWHERE and threw some logic into one that executed a very simple query against the database and returned the resulting queryset. The function I wrapped takes an argument that allows the invoking context to specify how many results to grab, directly in the template when I am using the template tag.
It is quite convenient - I don't have to update my view when I decide this list should have 5 items, not 3 - but it seems like one of those gray areas where we aren't supposed to tread (i.e. pushing application logic into templates) when writing good, maintainable Django code.
Now, a couple of hours separated from writing the code, I'm wondering if I should scrap the assignment_tag entirely.
Code:
models.py:
class SomeObject(models.Model):
is_active = models.BooleanField(default=False)
(...)
templatetags/myapp_tags.py:
from django import template
from myapp.models import SomeObject
register = template.Library()
#register.assignment_tag
def get_someobjects_list(max_results=0):
queryset = SomeObject.objects.filter(is_active=True)
if max_results == 0:
return queryset
elif max_results > 0:
return queryset[:min(max_results, queryset.count())]
else:
return None
templates/myapp/chunks/someobject_list.html:
{% load myapp_tags %}
{% get_someobjects_list as someobjects_list %}
# or {% get_some_objects_list 5 as someobjects_list %} ... flexible!
{% if someobjects_list %}
<ul>
{% for someobject in someobjects_list %}
<li>
<a href="{{ someobject.get_absolute_url }}">
{{ someobject.name }}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<span>No someobjects exist</span>
{% endif %}
I was really excited to discover these existed - it's convenient for me in this particular case. Now that my excitement over finding a new feature has passed, it seems pretty clear that I'm misusing it. The example given in the Django docs seems like a better application of this - grabbing the string representation of current datetime, something that doesn't require a DB query. My worry is that I'm setting myself up for heartache if I start using this pattern regularly. Following the slippery slope all the way down: I'll end up not even bothering to pass a context to my templates and ALL my DB queries will be hidden away in template tags where nobody would think to look for them.
It seems the code would be cleaner if I just threw out this whole "great idea" I had when I discovered assignment_tags and created a custom model manager instead.
Are there other clean ways of accomplishing this that I am missing? Are manager methods the consensus best way among Django developers?
assignment template tags are especially helpful if you need to get some information into the template context for a few pages of a website, but don't want to (or can't) put the info into every view on the website, and don't want to or can't rely on a context processor.
they basically guarantee that your information will be available in the template.

Make django url tag fail silently

The Django {% url %} templatetag raises a NoReverseMatch error when it can't reverse the provided URL. This is useful in development, but in production, this stops the user dead in their tracks with an ugly 500 error, blocking the whole page, and leading them to think our site is broken.
Template developers shouldn't be able to bring down the whole site with a typo. What I want to do is transparently override this behavior so that, in production only, if a reverse match can't be found, it outputs a default url, like "#", and reports the error to our exception tracking system in the background, but still lets the user continue with what they were doing without raising the 500 error.
Is there a way to replace the default {% url %} tag with my own safer version, transparently? I don't want to have to add a {% load my_custom_url_tag %} at the top of every single template on the site, because at some point people will forget, and the behavior of the tag is will otherwise be the same, the only difference is how it handles errors.
You can use the built-in url tag in silent mode, try the lookup, and then use the URL it finds—if it finds something.
From the Django docs:
This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you’ll use this to link to views that are optional:
{% url 'path.to.view' as the_url %}
{% if the_url %}
Link to optional stuff
{% endif %}
Hope that helps.
By implementing your own url tag, you're opening yourself up to lots of forward compatibility issues. My recommendation would be to add custom 500 error handler instead: https://docs.djangoproject.com/en/1.4/topics/http/views/#the-500-server-error-view
I would think you would actually want the view to throw an error if a template developer has made a typo. Trying to mask that behavior seems illogical - isn't that reason enough to have some simple unit tests to make sure your views are at least returning a 200 response code?

Django partial template responses

Is it considered correct/ are there any pitfalls in returning partial templates to ajax POST requests?
For example:
if request.is_ajax:
# response is just the form
return render(request, 'contact/fields.html', {'form':form})
The most typical approach is returning JSON and then contructing whatever HTML you need client-side from the JSON data. However, it could be argued that this is mixing presentation with behavior and it would be better to clearly separate out the HTML.
On the flip-side, returning a block of HTML is about as polar-south of "RESTful" as you can get. In pure REST philosophy, the views should return data in a standard and reusable container (such as JSON or XML). Later if you needed to pull the form into an iOS/Android/WP7/etc. app environment rather than a webpage, the JSON/XML will serve you just as well, whereas the HTML is virtually useless.
I can easily see both arguments, and I don't think one is necessarily more right than the other. Ultimately, I think you just have to do what works best for your app and what "feels right" to you. Think in terms of what is more maintainable and extensible for your particular circumstances.
I have no yet tried this with form POST request but very similarly we return partial HTML to AJAX GET request to do page changes without loading the whole page. I think it would work well for form request as well (we are in fact debating at the moment whether to use this approach on a page with multiple different forms).
I think if done right it is not a bad design pattern. We accomplish this by changing which base template is extended based on whether it was an AJAX call.
A simplified example:
### view
base_template = "base.html"
if request.is_ajax():
base_template = "base-ajax.html"
return render_to_response(request, 'page.html', {'base_template': base_template})
### page.html
{% extends base_template %}
{% block main %}new page content{% endblock %}
### base.html
<html>
<!-- complete html page -->
...
{% block main %}this is what changes per page{% endblock %}
...
</html>
### base-ajax.html
{% block main %}this is what changes per page{% endblock %}
I think most of my ajax return responses return DOM elements and not the entire form.
(an example)
...
person = ''' {1} {2}'''.format(p.id, p.first_name, p.last_name)
q = simplejson.dumps({"person":person})
return HttpResponse(q, mimetype="application/json")
The above sends back a simple DOM element to the template and inserts it into a table at the bottom. Sliding in right to left.
If you send back the entire template, the entire screen will flash and won't get any slick animations. That is my understanding anyway.
I have done this for a couple of jQuery Dialogs. The dialog contents are requested by a AJAX request, the contents are rendered on server side and then returned and displayed. So far I have experienced no problems with that.
From personal experience i can say that there is no pitfalls. I just not very good design pattern (not good practice). I used to do that on pretty high loaded project.
I have had the same problem in the year 2023 (question was asked in 2012..). Django still doesn't support rendering a template without invoking the whole chain of template inheritance.
So here's a basic way of rendering partial template:
from django.template import Context, loader
def render_template_to_string(template_name, context=None):
template = loader.get_template(template_name).template
context_instance = Context(context or {})
with context_instance.bind_template(template):
return template.nodelist.render(context_instance)
And your (partial) template can be as simple as:
<ul>my partial list
{% for opt in options %}
<li>{{ opt }}</li>
{% endfor %}
</ul>
You then invoke it by e.g.
from django.http import HttpResponse
resp = render_template_to_string(
"path/to/partial/html", {"options": range(10)}
)
return HttpResponse(resp)
FYI you might want to add support for some node exclusions, error handling, or better flexibility of what gets passed to render_template_to_string.

{% with %} templatetag to avoid query execution multiple times?

If I use for example {{ some_model.objects.all }} in several places in one template, will the query be executed each time? And if so, should I always use {% with some_model.objects.all as some_name %} to avoid that? I saw this in several apps, so I'm wondering if I understand it correctly.
Yes, it does repeat the query. You should populate the context in your view instead of calling these functions within the template.
Using {% with %} indeed does solve the problem though for future calls, but I still vote for the view.
PS:
I highly suggest downloading django-debug-toolbar
https://github.com/dcramer/django-debug-toolbar
You can test these ideas in a second : )

How do I create a filtered Dropdown Choice field in Django using ajax?

I am trying to create a dynamic filtered drop down choice fields,i gone through below blog but it confusing,can any one suggest easy way to do this in django.
I'm trying to create a dynamically filtered dropdown Choice field in Django. I've tried the steps outlined here, but I don't understand it.
How do I create a filtered Dropdown Choice field in Django using ajax?
You can use dajaxproject (django+ajax). Example: http://www.dajaxproject.com/forms/ It's so easy.
Maybe you mean something like this?
http://code.google.com/p/django-ajax-selects/
I have this implemented in a couple of projects, and it's working well. If you are looking for a kind of search form for foreign keys, have a look at an app I started some weeks ago:
https://github.com/schneck/django-foreignkeysearch
I only had a small array of drop down choices I needed to display, so I chose to be lazy and not to go the Ajax route but rather used the initial example provided in the blog (his prototype). This will slow down rendering the page if you have many drop-down choices, which I do not have.
The way it worked for me was that I replaced the array:
modelstxt[1] = "1\tEscort\n2\tTaurus";
modelstxt[2] = "1\tAltima\n2\tMaxima";
With template tags that will create the same array while building the page (note I use locations and areas, not models and makes):
areastxt[0] = "0\t--";
{% for location in locations %}
areastxt[{{location.id}}] = "0\t--
{% for area in areas %}
{% if area.location_id == location.id %}
\n{{area.id}}\t{{area.name}}
{% endif %}
{% endfor %}";
{% endfor %}
Disclaimer: I am noob'ish, so I may be committing a noob faux-pas using this approach.