Sunday, March 2, 2014

Dry pagination in template

From this Pagination sample....

If we have so many tables in the system, we paginate them and noticed that we're just repeating the codes. To make it dry...

Create a new template and named it pagination.html.


<a href="?page=1">First page</a>
{% for page in page_numbers %}
    {% if page == lists.number %}
    {{ page }}
    {% else %}
    <a href="?page={{ page }}">{{ page }}</a>
    {% endif %}
{% endfor %}
<a href="?page={{ lists.paginator.num_pages }}">Last page</a>

In your main templates call pagination.html, for example:


{% include "pagination.html" with lists=topics %}


{% include "pagination.html" with lists=employees %}

and so on.... That's it! :)

How to make a global request?

We can use request if we use views but how about in model method or other areas?

I've got this code from a blog last year (December) and I forgot the link. Here's the code:

import inspect

def get_request():
    """Walk up the stack, return the nearest first argument named "request"."""
    frame = None
        for f in inspect.stack()[1:]:
            frame = f[0]
            code = frame.f_code
            if code.co_varnames and code.co_varnames[0] == "request":
                return frame.f_locals['request']
        del frame




Python Error: object is not a json serializable

Level: Difficult


When I upgrade our system from Django 1.4 to Django 1.6, most of the request sessions and few installed apps I use are getting object is not a json serializable error. I cannot remove them because they are very important in the system.


I've search this problem and most of the ideas are creating a function that will catch the value with JsonSerializer. I've tried it and they worked in few areas but I need all affected functions be I search again. It takes weeks before I got the solution.

I've read a blog (I forgot the link) and he discussed about session. Then I checked the django documentation for further information. I've try to implement the function and got yeah! all my problem about json serializable are fixed.

Here it is:

Put this in your setting.

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

The solution above is for Django 1.6+. Browse Django Documentation for other version.


Sunday, February 9, 2014

Using exclude() in get()

Try this for testing:

    plan_type__in=["free", "trial"])

The above code will raise MultipleObjectsReturned if your query results in more than one matching set; which is likely to happen considering you are searching on something that isn't a primary key --- Burhan Khalid

To make it work, you must put exclude() before get().

YourModel.objects.exclude(plan_type__in=["free", "trial"]).get(

That's it!

Saturday, February 1, 2014

Using both POST and GET

I have a search function that use POST via Ajax. I've also use direct link to search data that use GET. To be able to use both POST and GET in searching data that I do not have to duplicate the codes for each of the request, here it is:

def search_options(request):
    if request.method == 'POST':
        method = request.POST
        method = request.GET
    if method.get('amount'):
        // search
    if method.get('name'):
        // search

def search_data(request):
    if request.method == 'POST':
        return HttpResponse("List updating...")

JS/Jquery not working after content loaded via AJAX

I experienced this problem when I use Ajax to save data. This is how to solve the problem....

When you load content via Ajax you must also load the scripts together with it.

    $('#sample').click(function() {
            type: "POST",
            data: dataString,
            url: url,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function(result) {
                $('#load_container').load(load_url, function(){ loadScripts(); });
            error: function(result) {

    $(document).ready(function() {
    function loadScripts() {
        $('#check-all').change(function() {  
            if(this.checked) {
                $(':checkbox').each(function() {this.checked = true;});
                $(':checkbox').each(function() {this.checked = false;});

Attach file in email message

I will use CSV as an example to attach it in an email. From this link: Creating CSV in Python...

from django.core.mail import EmailMessage

from .models import Employee
from .writers import csv_writer

def email_report(request):
    if request.method == 'POST':  
        email = request.POST.get('email')
        message = "This is a sample"  
        subject = "Test"
        mail = EmailMessage(subject, message,, [email])
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = "attachment; filename=filename.csv"
        fields = OrderedDict([
            ("First name", "first_name"),
            ("Last name", "last_name"),
            ("Phone", "phone"),
        response = csv_writer(response, Employee.objects.all(), fields)
        mail.attach("sample.csv", response, "text/csv")