Sonata create custom action - action

I follow the guide to create:
1. a action of sonata admin http://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_custom_action.html
2. a batch ax http://sonata-project.org/bundles/admin/master/doc/reference/batch_actions.html
In my action I want to change 1 field of the entity from true to false or via versa. For examble : the field enable. How can I update change to the database

I solve the a single action
However, with batch action when I load data from database with the code
$target = $modelManager->find($this->admin->getClass(), $request->get('idx'));
Sonata raise a notice "ModelManager ->find ('C4C\PlatformBundle\Entity\Member', array('1', '2', '3')) ". The reason is that Model Manage can not find an objec by an array.
How can I get all the objects from database based on an array

Related

Testing triggers for fulltext search in Django

I'm adding a search engine to a Django project, and thus set up SearchVectorFields on several models, with custom triggers.
I would like to unit-test that my columns of type TSVECTOR are updated when the instance of a Model changes.
However, I've been unable to find any information on how to test the content of a SearchVectorField ... I can't compare my_document.search to SearchVector(Value("document content")) or similar, because the first one seems to be string-like, while the latter is an object.
TL;DR
More precisely, with the model:
from django.db import models
class Document(models.Model):
...
content = TextField()
search = SearchVectorField()
and trigger:
-- create trigger function
CREATE OR REPLACE FUNCTION search_trigger() RETURNS trigger AS $$
begin
NEW.search := to_tsvector(COALESCE(NEW.content, ''))
return NEW;
end
$$ LANGUAGE plpgsql;
-- add trigger on insert
DROP TRIGGER IF EXISTS search_trigger ON myapp_document;
CREATE TRIGGER search_trigger
BEFORE INSERT
ON myapp_document
FOR EACH ROW
EXECUTE PROCEDURE search_trigger();
-- add trigger on update
DROP TRIGGER IF EXISTS search_trigger_update ON myapp_document;
CREATE TRIGGER search_trigger_update
BEFORE UPDATE OF content
ON myapp_document
FOR EACH ROW
WHEN (OLD.content IS DISTINCT FROM NEW.content)
EXECUTE PROCEDURE search_trigger();
How can I test that when I create a new Document instance, its search field is populated with the right values ? Same question for updating an existing Document instance, but the answer should be fairly similar.
Thanks for any hint ;)
I think you can compare string representation of your SearchVectorField values:
from django.test import TestCase
from .models import Document
class DocumentTest(TestCase):
def setUp(self):
Document.objects.create(content='Pizza Recipes')
def test_document_search(self):
document_list = list(Document.objects.values_list('search', flat=True))
search_list = ["'pizza':1 'recip':2"]
self.assertSequenceEqual(document_list, search_list)

How to correctly insert managed metadata term id using spservices updatelistitems

I have a sharepoint 2013 site that uses a managed metadata term set for navigation. Documents can be tagged with the managed metadata so they appear in whatever category or categories is appropriate for the document. I need to allow documents to be saved as favorites. I created a custom list that saves the file name and path but I can't get the managed metadata settings to save correctly. I am using spservices.UpdateListItems via javascript and pass the ids and terms in the valuepairs property of the call like so ;#. Although the method saves the record, it either does not save the term or it saves one completely unrelated. Does anyone have any further advice on how to do this?
$().SPServices({
operation: "UpdateListItems",
async: true,
batchCmd: "New",
listName: "UserFavorites",
valuepairs: [["Title", title], ["DocumentId", itemid],["AssetCategory", assetCategoriesString]],
completefunc: function (xData, Status) {
alert(Status + " -- " + xData.responseText);
}
});
Example of the assetCategoriesString variable contents:
"fc8d083a-fc5e-4525-8fef-04ba982d1633;#Print Publications"

Mongoid update association with existing documents, not creating a new one

I'm attempting to figure out how to elegantly update a document's associations with existing documents with Mongoid.
If I have Users and Groups, and want to assign a User to an existing group, how could I do this via update_attributes ?
I want to be able to do something like this:
user.attributes = { groups: [{"_id":"existing group id here"}]}
user.save
When I try to do the above, Mongoid attempts to INSERT a new group, thereby causing a ID duplicate error.
I have tried doing the same via nested attributes:
user.groups_attributes = [{"_id":"existing group id here"}]
user.save
And the same error occurs. Is there anyway I can do this WITHOUT having to manually query the group id and push it into the array? The reason I'm asking is because lets say i have a model with many associations.. i dont want to have to have blocks of code to update each association manually
Assigning an an existing User to an existing Group with update_attributes is very simple (assuming you already added the Group/User relation).
user.update_attributes(:group_id => 'existing group id here')

Wizard input - DB View - Dynamic where clause

I was trying to pass where condition values onto a database view.
View was created in init method of class defined.
Input to where clause was taken from a popped up wizard.
Issue is that the wizard form values are inserted into model bound database table.
This is happening on all submits.
Currently I am reading the latest record from table on wizard input.
And the view definition is modified to generate result set based on latest input record from wizard table.
select v.col1, v.expre2
from view_name v,
( select fld1, fld2 from wizrd_tbl_1 order by id desc limit 1 ) as w
where
v.colM between w.fld1 and w.fld2
Currently I am following the above sequence of steps and results are fetched.
But I think, this would fail if at least two users are using the same wizard concurrently.
How can I change my approach, so that
1. Wizard input is not sent to database table,
2. The inputs are sent to a where clause dynamically and the result set is bound to a List View
As a summary, I was trying to:
Creates a database view joining multiple table.
Take user input ( and saves in db table, which is not expected and
not required ).
Pass the user input to db view's where clause. ( Any alternative to wizard ? )
Bind the result set to List View
It is definitely a bad idea to morph a database view based on user input, when that view is likely to be accessed by multiple users.
The 'correct' way to do this would be to have a static database view which contains all possible records from the joined tables, and then filter that data for individual users by generating a "domain" and redirecting the user to a tree view with that domain applied.
You can redirect the user by creating a <button type="object"> which calls a function such as the below:
def action_get_results(self, cr, uid, ids, context={}):
# Redirect user to results
my_domain = ['&', ('col1','=','testval'), ('col2','>',33)]
return {
'type': 'ir.actions.act_window',
'name': 'Search Results',
'view_mode': 'tree',
'res_model': 'your.osv_memory.model.name',
'target': 'new', # or 'current'
'context': context,
'domain': my_domain,
}

how to set the default permission name created in Django?

I'm using django 1.6
Now when I define a model, it will create three permissions record for it (can_create, can_update, can_delete).
I'm now adding other permissions on the models (which doesn't matter in this question), and want to make a view to let the user assign them all to users and groups.
Now the problem is:
I want to replace the default name displayed for the three default created permissions.
Is there any way to do this?
Yes there is possibility to create custom permission while creating the models/table in django. But this will create the extra custom permission, by default 3 permission will create i.e( add, change, delete). One can create custom permission by following thing.
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)
The only thing this does is create those extra permissions when you run manage.py migrate (the function that creates permissions is connected to the post_migrate signal). Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:
user.has_perm('app.view_task')
One can see the django doc here django permission description
Based on this blog post and this Django ticket, I would say it is not possible and also not advisable to change these codenames (since they are used in the admin). It is however possible to change the human readable name (such as 'Can add permission')
I cannot add comment to the answers already there, hence adding a new answer.
I have been looking for a solution and could not find any. So I just make use of default permissions and use permissions to re-create them and use whatever name and codename you want. Django documentation here
class Foo(models.Model):
title = models.CharField(max_length=250)
class Meta:
default_permissions = ()
permissions = (
("add_foo", "Can add foo"),
("change_foo", "Can change foo"),
("delete_foo", "Can delete foo"),
("view_foo", "Can view foo"),
("list_foo", "Can list all foo")
)