Pass additional parameters to django_table2 TemplateColumn - django-tables2

In my django project I have a lot of tables which return models. The last column is mostly an Action-Column where users may edit or delete an instance. How do I proceed if I want to pass additional arguments to TemplateColumn if in some tables I want an edit and delete button and in other tables I only need an edit and info button? I want to use the same template.html but with conditions in it. Here what I have in Table:
import django_tables2 as tables
from select_tool.models import DefactoCapability
class DefactoCapabilityTable(tables.Table):
my_column = tables.TemplateColumn(verbose_name='Actions', template_name='core/actionColumnTable.html')
class Meta:
model = DefactoCapability
template_name = 'django_tables2/bootstrap-responsive.html'
attrs = {'class': 'table table-xss table-hover'}
exclude = ( 'body', )
orderable = False
And how do I check perms on the actions in order to display the button or not?

Quoting the TemplateColumn docs
A Template object is created [...] and rendered with a context containing:
record – data record for the current row
value – value from record that corresponds to the current column
default – appropriate default value to use as fallback
row_counter – The number of the row this cell is being rendered in.
any context variables passed using the extra_context argument to TemplateColumn.
So you could do something like this:
my_column = tables.TemplateColumn(
template_name='core/actionColumnTable.html',
extra_context={
'edit_button': True,
}
)
The context also contains the complete context of the template from where {% render_table %} is called. So if you have 'django.template.context_processors.request' in your context_processors, you can access the current user using {{ request.user }}.

Related

project clarity datagrid dynamic selection

Could someone help me out. I am trying to set dynamically the selection in the Project Clarity datagrid component.
https://vmware.github.io/clarity/documentation/v0.11/datagrid/selection
I have a filter which I am fetching from storage and I want to display the selection in the datagrid. Here is the code for populating the selected variable which is string array (string[])
selected: string[] = [];
I am console outputting the selected and it contains the correct values but those are not selected in the datagrid.
private initView() {
Object.entries(this.metadataFilter.metadataTypes).forEach(
([key, value]) => {
this.selected.push(key);
});
console.log('this.selected: ', this.selected);
}
this is what I have in the template:
<clr-datagrid [(clrDgSelected)]="selected">
Here is the population of the rows:
<clr-dg-row *clrDgItems="let meta of metadataTypes | async" (click)="getItemsForMetadataType(meta.name)" [clrDgItem]="meta">
<clr-dg-cell>{{ meta.name }}</clr-dg-cell>
</clr-dg-row>
It works when I am selecting entries from the grid. Those I get populated to a variable but not other way around. Help would be very much appreciated. Am I misunderstanding how this should work ?
There are two things to do here. First, I always recommend to use trackBy so you can be sure that the references are correct. Second, you need to put the whole object, not the key, into the selected array. The internal state of the data grid evaluates equality against references of the object, or if trackBy is used it computes the trackBy internally and evaluates equality between the references (like an ID or some string).
For example, this should initialize the 3rd item to be selected.
this.selected.push(this.metadataFilter.metadataTypes[2]);

How to bind Dropdown widget to query filter?

I have a Calculated Model, MonthlyTotalsByResource, displayed in a table that I am trying to query with a filter. First, I am retrieving the initial data from a regular Data Model called Allocations. I only wish to retrieve records from Allocations where the "Approved" field =true.
I also want to allow the user to filter MonthlyTotalsByResource by the "ManagerName" field. I have created a Dropdown widget with the Options as the full list of managers, and the Value is a query on the Calculated Model datasource:
#datasource.query.filters.ManagerName._equals
Here is the beginning of my code for getting the data for the Calculated Model MonthlyTotalsByResource from the regular data model Allocations, and where I filter for only "true" values in the Approved field. I am unclear what I should make the ManagerName filter set to in order for it to be binded to my Dropdown widget, or if I should add another query on the Calculated Model itself, instead of here on the regular Data Model.
function getMonthlyTotalsByResource_() {
var allRecordsQuery = app.models.Allocations.newQuery();
allRecordsQuery.filters.Approved._equals = true;
allRecordsQuery.filters.Resource.Manager.ManagerName._equals = ;
First things first, you need to introduce ManagerName parameter in your calculated datasource:
Once you add the parameter, you'll be able to set its value on client and read on server.
// dropdown widget's 'value' property binding
#datasources.MonthlyTotalsByResource.query.parameters.ManagerName
// server side code to get parameter value
var query = app.models.Allocations.newQuery();
...
query.filters.Resource.Manager.ManagerName._equals = query.parameters.ManagerName;
...

web2py orderby datetime out of order

I'm writing a simple web app in web2py that stores and retrieves some data from a database. To keep the entries in chronological order, my table has an attribute which stores a date time. Like so:
db.define_table('tablename',
Field( ....
....
....
Field('created_on','datetime', default=request.now, writable=False),
Field('last_modified','datetime', default=request.now, update=request.now),
)
Then when I request the data, I set the orderby attribute to last_modified:
rows = db().select(db.tablename.ALL, orderby=db.tablename.last_modified)
Then, I pass the results onto a Json dictionary object. Like so:
I'm passing them into a JSON dictionary object.Like so:
d = { r.index_id : {'index_id':r.index_id,
....
....
'comments':r.comments,
'created_on':r.created_on,
'last_modified':r.last_modified}
for r in rows}
return response.json(dict(entry_dict=d))
When I get the response from the server, I return the dict to my ractive object.
MAIN.set('data_entries', data['entry_dict']);
Then, I render the results in ractive:
{% #data_entries:index_id%}
<tr class = "datarow" onclick="window.document.location='{% url+ '/'+ index_id %}';">
<td>{% index_id %}</td>
....
<td>{% last_modified %}</td>
</tr>
{% /data_entries %}
However, when the data is returned to the webapp, I get to following:
Am I doing this right?
In Python, dictionaries do not preserve order, so when you convert the d dictionary to JSON, you will not necessarily get the keys in the order of the original Rows object. You could instead use an OrderedDict, but it doesn't appear you really need a dictionary anyway -- just create a list (using the as_list method):
return response.json(dict(entry_dict=rows.as_list()))
Then in Ractive, change:
{% #data_entries:index_id %}
to:
{% #data_entries %}
It doesn't appear you need the index value within each loop. Instead, you will be able to access the index_id field of each record as part of the data context of the section.

Include "Change Note" when creating content from InvokeFactory

I am creating a content item from a PloneFormGen Form Custom Script Adapter using invokeFactory. Everything is working fine so far, however we want to start generating a comment to be included in the create action, for the history of the item. The comment itself will be generated using fields from the form and some preset text.
Is this something that would be possible from PFG?
The content type is a custom type, and it is versionable. Using Plone 4.3.2, PFG 1.7.14
EDIT
My current code:
from Products.CMFPlone.utils import normalizeString
portal_root = context.portal_url.getPortalObject()
target = portal_root['first-folder']['my-folder']
form = request.form
title = "My Title: "+form['title-1']
id = normalizeString(title)
id = id+"_"+str(DateTime().millis())
target.invokeFactory(
"MyCustomType",
id=id,
title=title,
text=form['comments'],
relatedItems=form['uid']
)
I have tried using keys like comments, comment, message, and even cmfeditions_version_comment within the target.invokeFactory arguments. No luck so far.
I'm not sure if that's possible in a custom script adapter.
The action of you first entry is None. The history automatically shows Create if the action is None. This is implemented here (plone.app.layout.viewlets.content)
# On a default Plone site you got the following
>>> item.workflow_history
{'simple_publication_workflow': ({'action': None, 'review_state': 'private', 'actor': 'admin', 'comments': '', 'time': DateTime('2014/10/02 08:08:53.659345 GMT+2')},)}
Key of the the dict is the workflow id and the value is a tuple of all entries.
So you can manipulate the entry like you want. But I don't know if this is possible with restricted python (custom script adapter can only use restricted python).
But you could also add a new entry, by extending you script with:
...
new_object = target.get(id)
workflow_tool = getToolByName(new_object, 'portal_workflow')
workflows = workflow_tool.getWorkflowsFor(new_object)
if not workflows:
return
workflow_id = workflows[0].id # Grap first workflow, if you have more, take the the one you need
review_state = workflow_tool.getInfoFor(new_object, 'review_state', None)
history_entry = {
'action' : action, # Your action
'review_state' : review_state,
'comments' : comment, # Your comment
'actor' : actor, # Probably you could get the logged in user
'time' : time,
}
workflow_tool.setStatusOf(workflow_id, context, history_entry)

Meteor: How do I adjust iron router return data based on search query?

I have an app where users can take notes.
In the html page I iterate over each note like so:
<div id="notes-container" class="notes">
{{each notes}}
{{> note}}
{{/each}}
</div>
and in my router file I return the data like so:
#route: 'notes'.
path: '/notes/:_id',
data: ->
notes = Notes.find
threadId: #params._id
trash:
$exists: false
,
sort:
date: -1
All is typical meteor stuff so far. But I am confused now about how to adjust the data that is iterated on in the html page.
Each notes has a array field for tags like tags: ['apple' ,'red', 'green']
What if the user wants to return all notes with the tag 'red'. So there is a input box on the site the user enters a tag and presses enter.
How can I adjust the data that is sent to the page so queries mongodb to return all notes with tag red? I know how to write the query I am not sure how to set this up though in meteor.
One way I tried to do it is called the same route with query paramters like: '/notes/326363235474?tags=apple'
And in iron router I can look for query parameters and return the right set of documents but then when I call the original route again to clear the search, it does not load all of the original documents again.
Any suggestion on how I can set this up? Thanks
the data function simply needs to return the data you want available within the template context, if I'll define this function to a certain route:
data: ->
return Drawing.findOne
_id: window._drawing_id
I will have that data in my "this" object when proccessing that template.

Resources