<commit_before># Create your views here.
from django.db.models import get_model
from django.db import models
from django.shortcuts import render_to_response
from django.conf import settings

from dojango.util import json_response, to_dojo_data, json_encode
from dojango.decorators import json_response
from dojango.util import to_dojo_data
from dojango.util.form import get_combobox_data
from dojango.util.perms import access_model, access_model_field

import operator
    
# prof included for people using http://www.djangosnippets.org/snippets/186/
AVAILABLE_OPTS =  ('search_fields','prof','inclusions','sort','search','count','order','start')

@json_response
def datagrid_list(request, app_name, model_name, access_model_callback=access_model, access_field_callback=access_model_field):
    """
    Renders a json representation of a model within an app.  Set to handle GET params passed
    by dojos ReadQueryStore for the dojango datagrid.  The following GET params are handled with
    specially:
      'search_fields','inclusions','sort','search','count','order','start'
      
    search_fields: list of fields for model to equal the search, each OR'd together.
    search: see search_fields
    sort: sets order_by
    count: sets limit
    start: sets offset
    inclusions: list of functions in the model that will be called and result added to JSON
     
    any other GET param will be added to the filter on the model to determine what gets returned.  ie
    a GET param of id__gt=5 will result in the equivalent of model.objects.all().filter( id__gt=5 )
    
    The access_model_callback is a function that gets passed the request, app_name, model_name, and
    an instance of the model which will only be added to the json response if returned True
    
    The access_field_callback gets passed the request, app_name, model_name, field_name,
    and the instance.  Return true to allow access of a given field_name to model 
    app_name.model_name given instance model.
    
    The default callbacks will allow access to any model in added to the DOJANGO_DATAGRID_ACCESS
    in settings.py and any function/field that is not "delete"
    """
    
    # get the model
    model = get_model(app_name,model_name)
    
    # start with a very broad query set
    target = model.objects.all()
    
    # modify query set based on the GET params, dont do the start/count splice
    # until after all clauses added
    if request.GET.has_key('sort'):
        target = target.order_by(request.GET['sort'])
    
    if request.GET.has_key('search') and request.GET.has_key('search_fields'):
        ored = [models.Q(**{str(k).strip(): str(request.GET['search'])} ) for k in request.GET['search_fields'].split(",")]
        target = target.filter(reduce(operator.or_, ored))
    
    # custom options passed from "query" param in datagrid
    for key in [ d for d in request.GET.keys() if not d in AVAILABLE_OPTS]:
        target = target.filter(**{str(key):request.GET[key]})
    num = target.count()
    # get only the limit number of models with a given offset
    target=target[request.GET['start']:int(request.GET['start'])+int(request.GET['count'])]
    
    # create a list of dict objects out of models for json conversion
    complete = []
    for data in target:   
        if access_model_callback(app_name, model_name, request, data):   
            ret = {}
            for f in data._meta.fields:
                if access_field_callback(request, app_name, model_name,f.attname, data): 
                    ret[f.attname] = getattr(data, f.attname) #json_encode() this?
            fields = dir(data.__class__) + ret.keys()
            add_ons = [k for k in dir(data) if k not in fields and access_field_callback(request, app_name, model_name, k, data)]
            for k in add_ons:
                    ret[k] = _any(getattr(data, k))
            if request.GET.has_key('inclusions'):
                for k in request.GET['inclusions'].split(','):
                    if k == "": continue
                    if access_field_callback(app_name, model_name, k, request, data): 
                        ret[k] = getattr(data,k)()
            complete.append(ret)
        else:
            raise Exception, "You're not allowed to query the model '%s.%s' (add it to the array of the DOJANGO_DATAGRID_ACCESS setting)" % (model_name, app_name)
    return to_dojo_data(complete, num_rows=num)

#                                #########
#                                 # Tests #
#                                  #########

def test(request):
    return render_to_response('dojango/test.html')

@json_response
def test_countries(request):
    countries = { 'identifier': 'name',
                  'label': 'name',
                  'items': [
                      { 'name':'Africa', 'type':'continent', 'population':'900 million', 'area': '30,221,532 sq km',<commit_msg>added support for list_display to contain attributes in the form of the django ORM filters.  i.e. "test__name" will return the value of data.test.name<commit_after># Create your views here.
from django.db.models import get_model
from django.db import models
from django.shortcuts import render_to_response
from django.conf import settings

from dojango.util import json_response, to_dojo_data, json_encode
from dojango.decorators import json_response
from dojango.util import to_dojo_data
from dojango.util.form import get_combobox_data
from dojango.util.perms import access_model, access_model_field

import operator
    
# prof included for people using http://www.djangosnippets.org/snippets/186/
AVAILABLE_OPTS =  ('search_fields','prof','inclusions','sort','search','count','order','start')

@json_response
def datagrid_list(request, app_name, model_name, access_model_callback=access_model, access_field_callback=access_model_field):
    """
    Renders a json representation of a model within an app.  Set to handle GET params passed
    by dojos ReadQueryStore for the dojango datagrid.  The following GET params are handled with
    specially:
      'search_fields','inclusions','sort','search','count','order','start'
      
    search_fields: list of fields for model to equal the search, each OR'd together.
    search: see search_fields
    sort: sets order_by
    count: sets limit
    start: sets offset
    inclusions: list of functions in the model that will be called and result added to JSON
     
    any other GET param will be added to the filter on the model to determine what gets returned.  ie
    a GET param of id__gt=5 will result in the equivalent of model.objects.all().filter( id__gt=5 )
    
    The access_model_callback is a function that gets passed the request, app_name, model_name, and
    an instance of the model which will only be added to the json response if returned True
    
    The access_field_callback gets passed the request, app_name, model_name, field_name,
    and the instance.  Return true to allow access of a given field_name to model 
    app_name.model_name given instance model.
    
    The default callbacks will allow access to any model in added to the DOJANGO_DATAGRID_ACCESS
    in settings.py and any function/field that is not "delete"
    """
    
    # get the model
    model = get_model(app_name,model_name)
    
    # start with a very broad query set
    target = model.objects.all()
    
    # modify query set based on the GET params, dont do the start/count splice
    # until after all clauses added
    if request.GET.has_key('sort'):
        target = target.order_by(request.GET['sort'])
    
    if request.GET.has_key('search') and request.GET.has_key('search_fields'):
        ored = [models.Q(**{str(k).strip(): str(request.GET['search'])} ) for k in request.GET['search_fields'].split(",")]
        target = target.filter(reduce(operator.or_, ored))
    
    # custom options passed from "query" param in datagrid
    for key in [ d for d in request.GET.keys() if not d in AVAILABLE_OPTS]:
        target = target.filter(**{str(key):request.GET[key]})
    num = target.count()
    # get only the limit number of models with a given offset
    target=target[request.GET['start']:int(request.GET['start'])+int(request.GET['count'])]
    
    # create a list of dict objects out of models for json conversion
    complete = []
    for data in target:   
        if access_model_callback(app_name, model_name, request, data):   
            ret = {}
            for f in data._meta.fields:
                if access_field_callback(request, app_name, model_name,f.attname, data): 
                    ret[f.attname] = getattr(data, f.attname) #json_encode() this?
            fields = dir(data.__class__) + ret.keys()
            add_ons = [k for k in dir(data) if k not in fields and access_field_callback(request, app_name, model_name, k, data)]
            for k in add_ons:
                    ret[k] = _any(getattr(data, k))
            if request.GET.has_key('inclusions'):
                for k in request.GET['inclusions'].split(','):
                    if k == "": continue
                    if access_field_callback(app_name, model_name, k, request, data): 
                        try:
                            ret[k] = getattr(data,k)()
                        except:
                            try:
                                ret[k] = eval("data.%s"%".".join(k.split("__")))
                            except:
                                ret[k] = getattr(data,k)
            complete.append(ret)
        else:
            raise Exception, "You're not allowed to query the model '%s.%s' (add it to the array of the DOJANGO_DATAGRID_ACCESS setting)" % (model_name, app_name)
    return to_dojo_data(complete, num_rows=num)

#                                #########
#                                 # Tests #
#                                  #########

def test(request):
    return render_to_response('dojango/test.html')

@json_response
def test_countries(request):
    countries = { 'identifier': 'name',
                  'label': 'name',
                  'items': [
                      { 'name':'Africa', 'type':'continent', 'population':'900 million', 'area': '30,221,532 sq km',
{'fraction_non_alphanumeric': 0.09673305209457471, 'fraction_numerical': 0.003139409398606887, 'mean_word_length': 2.732698645184914, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2174593', 'n_tokens_mistral': 2935, 'n_tokens_neox': 2848, 'n_words': 953}