Skip to main content

Posts

Showing posts with the label filter

Django template tags to find out field type

Sometimes you have the task to decorate django form fields. In our case it was need to add different widget to form field depending on field type. You can know your field type by refering to it's python class name, e.g.: field . __class__ . __name__ You will get wrong symbols error if you try to refer this python variable in templates directly. So you need a custom template tag to serve here. Decision was not to return variable for tag but to add context variable, cause I had need to perform exact actions on certain field types. So tag example: @register . simple_tag ( takes_context = True ) def set_this_field_type ( context , field ) : """     Adds to context given field type variable     variable named "this_field_type"     """ context [ "this_field_type" ] = field . field . __class__ . __name__ return '' Now you can add this variable to your if statements. E.g. usage: {% ...

Django: Adding news archive. Querying models with date and time filtering.

Today I had some practice with filtering Django models by date. Task was to archive old entries of the news. I've made 2 separate views for those. I was displaying actually news and another was ment to display archived items. Quite common task I guess. Also those 2 views are under wired buggy CMS, but we are not talking about that now. Will save some examples for future of mine/someones usage. Time. Subtracting a year from today with Python dateutil : from datetime import date , timedelta d = date . today ( ) - timedelta ( days = days_to_subtract ) This example returns 'd' that has less days than specified in 'days_to_subtract' . timedelta function also can be fed with 'months' , 'years' and so on. Becomes handy during time calculations. If you change this minus into plus you can calculate future time. Filtering Querysets. Filtering by date ranges. samples = Sample . objects . filter ( date__gte = datetime . date ( 2011 , 1...