Sonata Admin Bundle saving non-associated record - doctrine-orm

I need to persist an object of non-associated entity in the postPersist callback in Sonata Admin. I am not able to get $em = $this->getDoctrine()->getEntityManager(); in the Sonata Admin.

You can use $this->getModelManager()->create($object); to persist any object in Sonata Admin Bundle.

You can use this one too similar to Baran answer
$query = $this->getModelManager()->createQuery('AppBundle:testEntity', 'entity');
$results = $query->execute();

Related

How to update a Foreign Key value in Flask Sqlalchemy?

class VehicleModel(db.Model):
__tablenam__ = 'vehicle'
id = db.Column(db.Integer,primary_key=True)
class DriverModel(db.Model):
__tablename__ = 'driver'
id = db.Column(db.Integer,primary_key=True)
v_id = db.Column(db.Integer,db.ForeignKey('vehicle.id'))
v_rel = db.relationship('VehicleModel',backref=db.backref('vehicle',uselist=False))
def update(self,id,v_id):
self.id = id
self.v_id = v_id
db.session.commit()
In this above code, i am not able to update the value of v_id. Sqlalchemy is not throwing any sql error either. I don't know, the update method is working fine but not able to update v_id value. The value of v_id remains same as it was set when adding the column for first time.
This is because Alembic can’t do particularly detailed checks on your dB.Models do you have to change the migration script yourself. If you’re using Flask-migrate it’ll be in a migrations/versions folder. Change this using the alembic syntax found elsewhere in the file to change a foreign key.
Well it worked automatically after making certain changes in the relation, so never mind!
And thank you all for your responses!

Dynamically created proxy models do not have listed permissions on admin site

Here is my models.py:
class Item(models.Model):
# ... some irrelevent fields ...
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = models.CharField(max_lenght=30)
category_id = models.IntegerField()
Tag is actually a general-purpose name. Each item has many different type of tags - currently there are four types: team tags, subject tags, admin tags and special tags. eventually there will probably be a few more.
The idea is, they all have basically the same fields, so instead of having like 4 tables with manytomany relationship, and instead of adding a new column for Item whenever adding a new type, everything is called a 'tag' and it's very easy to add new types without any change to the schema.
Now to handle this in the admin.py I'm using dyamically created proxy models (based on this), as such:
def create_modeladmin(modeladmin, model, name = None):
class Meta:
proxy = True
app_label = model._meta.app_label
attrs = {'__module__': '', 'Meta': Meta}
newmodel = type(name, (model,), attrs)
admin.site.register(newmodel, modeladmin)
return modeladmin
class TagAdmin(models.Model):
def queryset(self):
return self.model.objects.filter(category_id = self.cid)
class TeamAdmin(TagAdmin):
cid = 1
class SubjectAdmin(TagAdmin):
cid = 2
# ... and so on ...
create_modeladmin(TeamAdmin, name='Teams', model=Tag)
create_modeladmin(SubjectAdmin, name='Subject', model=Tag)
#... and so on ...
This works great for me. However, different staff members need different editing permissions - one guy shouldn't access admin tags, while the other should only have access to edit subject-tags and team-tags. But as far as the admin site is concerned - the dynamic models do not exist in the permission list, and I can't give anyone permissions regarding them.
i.e. a user given all permissions on the list will still not have access to edit any of the dynamic models, and the only way to let anyone access them at all is to give him a superuser which obviously defies the point
I searched SO and the web and I can't anyone with a similar problem, and the docs don't say anything about this not in the dynamic models section or the proxy models section. so I'm guessing this is a different kind of problem. Any help would be greatly appreciated
UPDATE
So after some research into it, the answer was simple enough. Since permissions in django are objects that are saved to the database, what I needed to do was simple - add the relevent permissions (and create new ContentType objects as well) to the db, and then I could give people specific pemissions.
However, this raised a new question - is it a good convention to put the function that creates the permissions inside create_modeladmin as a find_or_create sort of function (that basically runs every time) or should it be used as an external script that I should run once every time I add a new dynamic model (sort of like how syncdb does it)?
And is there a way to also create the permissions dynamically (which seems to me like the ideal and most fitting solution)?
of course you can create permissions, django have django.contrib.auth.management.create_permissions to do this

How to only sync custom permissions with syncdb?

Is it possible to have the manage.py syncdb command ONLY sync custom permissions to the auth_permission table? I don't want the default three permissions installed for the app models, i.e. foo.add_bar, foo.change_bar, foo.delete_bar. I specify my custom permissions in my model classes like the django documentation suggests:
class Meta:
permissions = (
("admin", "Can create/edit/delete projects"),
("user", "Can view projects"),
)
Thank you!
You have 2 solutions here, AFAIK :
manually insert in the auth_permission table ;
Add in a command this snippet.
Adding a command is pretty straightforward. Just create a module sync_perms.py (with the snippet code) in a management.commands package in one of your apps (here the official documentation).
Then run :
python manage.py sync_perms
Et voilà !
Just posted the solution to
Remove (or hide) default Permissions from Django.
The idea is not to prevent them from being created by syncdb, but to hide them from the admin interface.
first you must find the content type id for your application the content type
can be found with this query
select * from django_content_type;
then you execute the query to add to database the custom permission you want for example
insert into auth_permission(name,content_type_id,codename) values
('Can add name',12,'can_add_name');
in the above query , name is a string which the user see in permissions list , the number is the application id found from the first query and codename is the code that you will use in templates for example in template you can use
{{perms.application.can_add_name}}
You need to specify default_permissions on Meta to be empty tuple. (default value is ('add', 'change', 'delete')). Docs.
class MyModel(models.Model):
# properties definition...
class Meta:
permissions = (
("admin", "Can create/edit/delete projects"),
("user", "Can view projects"),
)
default_permissions = ()
I also like to have special MyAppProperties model with Meta.managed=False to hold my app-wide permissions.
class MyAppPermissions(models.Model):
# properties definition...
class Meta:
managed = False
permissions = (
("admin", "Can create/edit/delete projects"),
("user", "Can view projects"),
)
default_permissions = ()
this way it won't create a database table, but permissions for it. Docs.

django - create user from request

I need some help with django request
I want to add a custom form proccessing to add a user (or any other model instance)
I don't want to create it like this
tagName = request.POST["tagname"]
new_tag = Tag()
new_tag.name = tagName
new_tag.save()
because I would need to rewrite this code everythime something changes in the model
Is there any way how can I create a model instance from the request?
What is the way django-admin do this?
Thank you so much
Use ModelForms

Object label in GAE Django

In my usual django code I use the unicode function to give each object a label...this appears in the admin interface as the oject label in the objects listed...
class apprd(models.Model):
usr = models.ReferenceProperty(User)
approved = models.BooleanProperty(default = True)
def __unicode__(self):
return ('approved one')
but now i have moved to GAE and this feature does not seem to be supported...
is there any work around or am I doin a mistake
This isn't possible in GAE, because the GAE admin console does not read - indeed, has no access to - your model definitions. It only has access to the stored data.
If you use http://code.google.com/p/app-engine-patch/, you can get the full Django admin interface running inside GAE.