Translate

Friday 16 May 2014

Django template filter

Django Tutorial: Making Your Own Template Filters


Django template tags and filters are huge time-savers and help you keep your presentation logic DRY and easy to maintain. Tags and filters are just small bits of code that allow you to perform formatting and simple presentation-related logic right in your template. Django filters are simple Python functions that accept a value, an optional argument, and return a value to be displayed on the page.

In this tutorial we will be creating a custom filter which will return the value of list at particular index.

First of all, you'll want to create a directory for holding your custom template filters. This is a requirement: custom template filters must live inside a Django app. Note that if you plan on building a small library of custom tags or filters, to be used across an entire project, you could create a Django app just for holding these files. If not, keep it simple: each app gets a templatetags directory at the same level as the models and views.
You'll want this directory to be recognized as a Python package, so make sure you create an empty __init__.py file. Next, go ahead and create the Python file that will hold your tags and name it something like custom_filters.py or a similar name that is easily identifiable.
Here is what the folder structure should look like:
Django Project
  -> my_app
    ---> models.py
    ---> views.py
    ---> templatetags
      -----> __init__.py

      -----> custom_filters.py

To get started, we'll need some imports at the top of our custom_filters.py file.

from django import template
from datetime import date, timedelta


register = template.Library()

register = template.Library() makes sure that your templates are added to the existing library of tags and filters that Django knows about. You can use the handy @register decorator and pass in the name of your filter to register it with Django.

@register.filter(name="value_at_index")
def value_at_index(list, index):
    try:
        return list[index]
    except:
        return -1

Then in the template where you want to use this template put {%  load value_at_index  %} at the top, then use as following:

{% for city in cities %}
    ...
     <p> The name of city is  {{ city }} and country is {{ countries|value_at_index:forloop.counter0  }}</p>
    ...

{% endfor %}

Where countries is also a list. In this way one can write a custom filter and one should be sure to handle all the exceptions that might occur.

Thursday 15 May 2014

Django


Learning Django


Template Query Debug:

This snippet show you which queries were run while generating the current page, but they'll start out hidden so as not to be a pain.
Of course, before this works, you'll need to satisfy all the criteria for getting debug information in your template context:
Have 'django.core.context_processors.debug' in your TEMPLATE_CONTEXT_PROCESSORS.Have your current IP in your INTERNAL_IPS setting.Use RequestContext when rendering the current template (if you're using a generic view, you're already using RequestContext).

{% if debug %}
<div id="debug">
  <h2>Queries</h2>
  <p>
    {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}
    {% ifnotequal sql_queries|length 0 %}
    (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
    {% endifnotequal %}
  </p>
  <table id="debugQueryTable" style="display: none;">
    <col width="1"></col>
    <col></col>
    <col width="1"></col>
    <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">SQL</th>
      <th scope="col">Time</th>
    </tr>
    </thead>
    <tbody>
    {% for query in sql_queries %}<tr class="{% cycle odd,even %}">
      <td>{{ forloop.counter }}</td>
      <td>{{ query.sql|escape }}</td>
      <td>{{ query.time }}</td>
    </tr>{% endfor %}
    </tbody>
  </table>
</div>
{% endif %}

Source: https://djangosnippets.org/snippets/93/

Wednesday 14 May 2014

Python interview questions

Python Interview Questions and Answers

1.  How are arguments passed – by reference of by value?                                                                 

First of all you can not say “it is by value or by reference”, because there is no such a thing in Python. May be more clear answer will be something like this (there is no short answer): Python works differently compared to other languages and there is no such a thing like passing an argument by reference or by value. If we want to compare it it will be closer to passing by reference because the object is not copied into memory instead a new name is assigned to it.

2.  Do you know what list and dict comprehensions are? Can you give an example?


List/Dict comprehensions are syntax constructions to ease the creation of a list/dict based on existing iterable.

# simple iteration
a = []
for x in range(10):
    a.append(x*2)
# a == [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# list comprehension
a = [x*2 for x in range(10)]

# dict comprehension
a = {x: x*2 for x in range(10)}
# a == {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}


3.  What is PEP 8?


PEP 8 is a coding convention(a set of recommendations) how to write your Python code in order to make it more readable and useful for those after you.

4.  Can you sum all of the elements in the list, how about to multuply them and get the result?


# the basic way
s = 0
for x in range(10):
    s += x

# the right way
s = sum(range(10))

# the basic way
s = 1
for x in range(1, 10):
    s = s * x

# the other way
from operator import mul
reduce(mul, range(1, 10))

5.  Do you use virtual environments?


A Virtual Environment, put simply, is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects.

For example, you can work on a project which requires Django 1.3 while also maintaining a project which requires Django 1.0.

6.  Can you sum all of the elements in the list, how about to multuply them and get the result?



# the basic way
s = 0
for x in range(10):
    s += x
# the right way
s = sum(range(10))
# the basic way
s = 1
for x in range(1, 10):
    s = s * x
# the other way
from operator import mul
reduce(mul, range(1, 10))

7.  Do you know what is the difference between lists and tuples? Can you give me an example for their usage?


First list are mutable while tuples are not, and second tuples can be hashed e.g. to be used as keys for dictionaries. As an example of their usage, tuples are used when the order of the elements in the sequence matters e.g. a geographic coordinates, “list” of points in a path or route, or set of actions that should be executed in specific order.

8.  Do you know the difference between range and xrange?


Range returns a list while xrange returns a xrange object which takes the same memory no matter of the range size. In the first case you have all items already generated(this can take a lot of time and memory) while in the second you get the elements one by one e.g. only one element is generated and available per iteration.

9.  Tell me a few differences between Python 2.x and 3.x ?


There are many answers here but for me some of the major changes in Python 3.x are: all strings are now Unicode, print is now function not a statement. There is no range, it has been replaced by xrange which is removed. All classes are new style and the division of integers now returns float.

10.  What are decorators and what is their usage?


“Decorators allow you to inject or modify code in functions or classes”. In other words decorators allow you to wrap a function or class method call and execute some code before or after the execution of the original code. And also you can nest them e.g. to use more than one decorator for a specific function. Usage examples include – logging the calls to specific method, checking for permission(s), checking and/or modifying the arguments passed to the method etc.

11.  The with statement and its usage.


In a few words the with statement allows you to executed code before and/or after a specific set of operations. For example if you open a file for reading and parsing no matter what happens during the parsing you want to be sure that at the end the file is closed. This is normally achieved using the try… finally construction but the with statement simplifies it usin the so called “context management protocol”.