how to log model inserts,updates and deletes in django - python

how to log model inserts,updates and deletes?
I am not using django admin,in my app there are multiple tables
i just want to records only which model or table name, field name,previous value,who edited,and what time
to log table?
Who edited (my app uses SSO,it should pick up remote user automatically)
can you please suggest any built in function or module in django to records this kind of logs ,if possible can you plz add few lines of django code or any ref links?
Thanks in advance

You can try this:
from django.db.models.signals import post_save
def logging_function(sender, **kwargs):
# do your logging
post_save.connect(logging_function)

Python has a logger http://docs.python.org/library/logging.html What's wrong with that?
You can, also, add an event table to your Django models and write to that table.
For real fun, you can create a decorator which writes to that table.
You can search, too. You'll find things like this: http://djangosnippets.org/snippets/2111/

Related

Django: send notifications at user based on database change

I have 3 database tables:
users (stores info about users e.g. email, name)
metadata (stores data)
activity (stores changes made to users/metadata tables)
I want to achieve the following:
to store any change into the activity table (e.g. new user is created, a user updates the metadata table)
to send notifications to users whenever a change into the users/metadata tables happens.
What are the libraries/method that I could use in order to achieve the desired functionalities? Thank you!
in addition to django signals which wes already recommended, you can also check out django channels + django activity stream
Assuming you are making use of the Django Models, I would use the Django Signals for saving the data to a second model: "MetaData" according to your question.
Specifically the post_save signal:
https://docs.djangoproject.com/en/4.0/ref/signals/#django.db.models.signals.post_save
#receiver(post_save, sender=User)
def post_save_user(sender, instance, created, **kwargs):
# Save Stuff To Metadata Model.
meta = MetaData(user=instance)
meta.save()
You need to import those signals inside your models.py placed at the bottom of the file.
As for the notifications, I would follow #kristina's advice and use Django Channels.
Just remind that your application needs to be ASGI (Async). So your application server needs to be one like uvicorn, daphne, hypercorn, etc.

How to perform a model that represents an existing table or a database view?

I'm trying to create a database view from django instead of associate a model from an existing database table. I'm new in django world and i don't know how how can i do this. Anyone have any ideia where to start look to solve this? Maybe this is not possible but can you see any alternative solution?
I understand how to define a model that as no management, by consider managed=False like i found on django docs, but how can i create an customized SQL view in my model class?
something like this:
Class myModel(models.Model):
Object = models.raw("CREATE VIEW foo AS SELECT * FROM table.A")
class Meta:
db_table = 'myview\".\"mymodeltable'
managed = False
With inspectdb management command, you can obtain the models definition from existing tables. To do that, you need to configure your settings.py file to have access to the database you want to work with and then do:
python manage.py inspectdb > models.py
You will see that it also automatically sets the managed=False. From that point, you can start querying its objects with typical objects.all(), objects.filter() and this stuff
Note: Don't forget to add the app with the imported models to the INSTALLED_APPS variable of your settings.py file.
Unfortunately maybe this is the final answer that can be found on DjangoDocs
This is useful if the model represents an existing table or a database view that has been created by some other means.

how to make dynamic field creation capability in openerp module?

Hi I have created an openerp module using Python (eclipse) . I want to add a feature in my form so that admin will be able to create his own fields whenever and whatever he wants . I needed some guidance of how this will be done . As I am new to openerp , any help will be good to me . Thanks
Hopes for advice
I can't think of any easy way of doing this. When OpenERP connects to a database it sets up a registry containing all models and all the fields and as part of this, loads the fields into the database, performs database refactoring etc. The idea is that it is simple to inherit existing models and add your fields that way but it does require coding.
I have done something similar where:
I predefined some fields on your model (field1, intfield1, charfield1 etc.).
Provide a model/form so the admin can say use intfield1 and give it a label of 'My Value'
Override fields_view_get on your model and change the XML to include your field with the correct label.
But this is tricky to get right. You will want to spend some time learning the elementtree module to do the XML manipulation in the fields_view_get.

Which is the best way to log user actions in flask views?

I would like to log user actions whenever user logs in/out and adds, edits, deletes objects in my site models in flask. Which is the best way to do this? Also I would like to show the old data and the new modified data, which happens using wtfforms. I am using flask and Flask-SQLAlchemy. I want something similar to what Django framework offers in the 'History' hlink for the associated objects.
Use Signals. Take a look at this
http://flask.pocoo.org/docs/signals/
Using signals, you can keep track of any actions such as adds/edits etc. as needed. All you have to do is
from blinker import Namespace
my_signals = Namespace()
def add_user():
# add user code here
user_added = my_signals.signal('user-added')
You can refer to flask-login, also using Signals.

Do I need to create a separate class in my models.py when using the django.contrib.auth.models import user?

The import statement import the needed parts. but is the "user" class already made when you put that into your installed apps? or do you still need to clarify in models.py in order to make the table in the db? or can someone expand on how to use django users and sessions? I'm looking over the django docs right now and they all just go over how to use the thing once. they never put the code in a syntax where users are going to be the ones using the code through a browser and not you through a python shell.
All installed apps can contribute to the database schema. django.contrib.auth.models contributes, among others, the auth_user table behind the django.contrib.auth.models.User model, therefore you do not have to worry about recreating it unless you have a specific reason to do so.
There's a number of things going on here. As you're aware, Django comes with a number of "contrib" packages that can be used in your app. You "activate" these by putting them into your INSTALLED_APPS.
When you run python manage.py syncdb, Django parse the models.py files of every app in INSTALLED_APPS and creates the associated tables in your database. So, once you have added django.contrib.auth to your INSTALLED_APPS and ran syncdb, the tables for User and Group are there and ready to be used.
Now, if you want to use these models in your other apps, you can import them, as you mention, with something like from django.contrib.auth.models import User. You can then do something like create a ForeignKey, OneToOneField or ManyToManyField on one of your models to the User model. When you do this, no tables are created (with the exception of ManyToManyField; more on that in a bit). The same table is always used for User, just as for any of your own models that you might create relationships between.
ManyToManyFields are slightly different in that an intermediary table is created (often called a "join table") that links both sides of the relationship together. However, this is purely for the purposes of that one particular relationship -- nothing about the actual User table is different or changed in any way.
The point is that one table is created for User and this same table is used to store all Users no matter what context they were created in. You can import User into any and all of your apps, create as many and as varied relationships as you like and nothing really changes as far as User is concerned.
If the table name or something else does not fit in your needs you can always just extend the User model.
from django.contrib.auth.models import User
class Employee(User):
...
Any class extending Model class in models.py contributes to database schema. That means, django search your (and also django core) model.py files and looks for any class that extends Model like:
some models.py
class SomeModel(Model):
...
...
class Otherthing(Model):
...
that is also applies for django core code files. Since all Database tables named using application label and model name, database ables created by django also have that...
For example,
from django.contrib.auth.models import User
If you track file hierarchy django -> contrib -> auth and open models.py file, you will see related model. Ther are also other Model classes in here, like Permission and Group models.
Since these models are under auth application, database tables are auth_user, auth_perission and auth_group
When you run manage.py syncdb command for the first time, django will create these tables...

Categories

Resources