Login

Group results by a range of dates in admin sidebar with calendar

Author:
coolchevy
Posted:
January 31, 2011
Language:
Python
Version:
1.2
Score:
0 (after 2 ratings)

Adds filtering by ranges of dates in the admin filter sidebar.

https://github.com/coolchevy/django-datefilterspec

http://coolchevy.org.ua

https://github.com/coolchevy/django-datefilterspec/raw/master/datefilter.png

Example:

` from django.db import models import datefilterspec class Person(models.Model): date = models.DateTimeField(default=datetime.datetime.now) date.date_filter = True

class Admin: list_filter = ['date']

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Adds filtering by ranges of dates in the admin filter sidebar.

https://github.com/coolchevy/django-datefilterspec

Example:

from django.db import models
import datefilterspec
 
class Person(models.Model):
    date = models.DateTimeField(default=datetime.datetime.now)
    date.date_filter = True

    class Admin:
        list_filter = ['date']
"""

__author__ = "Vitalii Kulchevych  <[email protected]>"
__date__ = "01 Feb 2011"
__all__ = ["DateFilterSpec"]


import datetime
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.admin.filterspecs import FilterSpec, DateFieldFilterSpec
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminDateWidget


class DateForm(forms.Form):

    def __init__(self, *args, **kwargs):
        field_name = kwargs.pop('field_name')
        super(DateForm, self).__init__(*args, **kwargs)
        self.fields['%s__gte' % field_name ] = forms.DateField(label=(_('From')),widget=AdminDateWidget,required=False)
        self.fields['%s__lte' % field_name ] = forms.DateField(label=(_('To')),widget=AdminDateWidget,required=False)
        for k in kwargs.get('initial',{}):
            if not self.fields.has_key(k):
                self.fields[k] = forms.CharField(widget=forms.HiddenInput())
                self.fields[k].inital = kwargs.get('initial').get(k)


class DateFilterSpec(DateFieldFilterSpec):

    def __init__(self, f, request, params, model, model_admin):
        super(DateFilterSpec, self).__init__(f, request, params, model,
                                                   model_admin)
        self.field_generic = '%s__' % self.field.name

    def title(self):
        title = super(DateFilterSpec, self).title()
        form = DateForm(initial=self.params, field_name=self.field.name)
        out =  u"""
        <style>
            .calendarbox {
                /*left:0 !important;*/
                z-index:1100;
        }
        </style>
        <form method="GET" action="">
        <link rel="stylesheet" type="text/css" href="%(admin_media)scss/forms.css" />
        <link rel="stylesheet" type="text/css" href="%(admin_media)scss/widgets.css" />
        %(form_media)s
        <ul>
        %(form)s
        <li> <input type="submit" value="%(search)s"> </li>
        </ul>
        </form>
        """ % {'search':_('Go'),'form_media':form.media,'form':form.as_ul(),'admin_media':settings.ADMIN_MEDIA_PREFIX}
        return mark_safe(title) + mark_safe(out)
        

# register the filter
FilterSpec.filter_specs.insert(0, (lambda f: hasattr(f, 'date_filter'), DateFilterSpec))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

jazzuell (on July 3, 2011):

The example doesn't work on my server. Problem is in date = models.DateTimeField(default=datetime.datetime.now). There is no class DateTimeField in models. Isn't the example correct, or am I using this wrong? Do I need download some additional modul with DateTimeField? I am using Django 1.3 Beta.

Thank you for any response.

P.S. I am trying to filter with HTML input textfield, can you help me a little with modifying code above plese?

#

dPeS (on July 21, 2011):

junk code, never tested, beware

#

coolchevy (on August 16, 2011):

jazzuell, default=datetime.datetime.now is not required, This is django 1.2 example.

dPeS, wtf? it works in production https://github.com/coolchevy/django-datefilterspec/raw/master/datefilter.png :)

#

Please login first before commenting.