Giter Site home page Giter Site logo

jazzband / django-simple-history Goto Github PK

View Code? Open in Web Editor NEW
2.1K 44.0 467.0 2.66 MB

Store model history and view/revert changes from admin site.

Home Page: https://django-simple-history.readthedocs.org

License: BSD 3-Clause "New" or "Revised" License

Makefile 0.16% Python 98.76% HTML 1.07%

django-simple-history's Introduction

django-simple-history PyPI Version

Jazzband Build Status Documentation Status Test Coverage Maintainability Code Style Downloads

django-simple-history stores Django model state on every create/update/delete.

This app supports the following combinations of Django and Python:

Django Python
4.2 3.8, 3.9, 3.10, 3.11, 3.12, 3.13-dev
5.0 3.10, 3.11, 3.12, 3.13-dev
main 3.10, 3.11, 3.12, 3.13-dev

Getting Help

Documentation is available at https://django-simple-history.readthedocs.io/en/stable/

Pull requests are welcome. Read the CONTRIBUTING file for tips on submitting a pull request.

License

This project is licensed under the BSD 3-Clause license.

django-simple-history's People

Contributors

barm avatar buddylindsey avatar cuducos avatar ddabble avatar dependabot[bot] avatar dnozay avatar erikvw avatar foobacca avatar gbataille avatar hramezani avatar hugovk avatar jeking3 avatar jezdez avatar joaojunior avatar joshuadavidthomas avatar jwhitlock avatar kseever avatar legau avatar leportella avatar macro1 avatar marcanuy avatar matklad avatar pre-commit-ci[bot] avatar q avatar realorangeone avatar smithdc1 avatar tim-schilling avatar treyhunner avatar valberg avatar wizpig64 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-simple-history's Issues

TypeError 'company_id' is an invalid keyword argument for this function

I get this error here:

def create_historical_record(self, instance, type):
...
    manager.create(history_type=type, changed_by=changed_by, **attrs)
....

My Model is:

class Department(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('Company'))
    name = models.CharField(_('Department name'), max_length=200)
    description = models.TextField(_('Department description'))
    size = models.PositiveIntegerField('Department size mq.')

    history = HistoricalRecords()

Where am I wrong?

Thank you

ForeignKeys get not resolved when using all()

When trying to access a ForeignKey while iterating over all history objects using all() I get the following exception:

AttributeError: 'HistoricalB' object has no attribute 'baz'

The code below shows the problem:

models.py:

from django.db import models
from simple_history.models import HistoricalRecords

class A(models.Model):
    foo = models.CharField(max_length=255)

class B(models.Model):
    baz = models.ForeignKey('A')
    history = HistoricalRecords()

views.py:

from models import B

def print_history(request):
    x = B.get.objects(pk=1):
    print x.baz.foo         # works

    print x.history.most_recent().baz.foo       # works

    for y in x.history.all():
       print y.baz.foo      # doesn't work

[...]

History diff

Is there a way to compare 2 history objects and return their difference?

NoReverseMatch {{ action.revert_url }}

Hello,

We get a "NoReverseMatch" error in the following file:

simple_history/templates/simple_history/object_history.html

The error occurs in the following line (action.revert_url):

<td><a href="{{ action.revert_url }}">{{ action.history_object }}</a></td>

I have installed the plugin via pip, added the "simple_history" application to the settings.py, modified the objects to include the history property, registered an admin site for the objects. The data revisions are stored correctly, but when clicking the "history" link the above error occurs?

No history found in admin when underscore in models primary key

Dear Trey,

first of all thanks for this awesome library!

I think I might have found a minor bug in django-admin, when underscore in primary key is used. Similar issue was reported here https://code.djangoproject.com/ticket/18381.

Problem is on the line 55 in the https://github.com/treyhunner/django-simple-history/blob/master/simple_history/admin.py in the history_view.

 def history_view(self, request, object_id, extra_context=None):
        "The 'history' admin view for this model."
        model = self.model
        opts = model._meta
        app_label = opts.app_label
        pk_name = opts.pk.attname
        history = getattr(model, model._meta.simple_history_manager_attribute)

        # problem is on this line, since for lookup is used 'quoted' object_id
        action_list = history.filter(**{pk_name: object_id})


        # This line works just fine, since unquote is used on the object_id
        obj = get_object_or_404(model, pk=unquote(object_id))
        ...

Do you think you could fix it, or should I create a pull request? Please let me know.
This is my first reported issue on github, so please, be patient with me :)

Again, thanks a lot for all your great work!

Adam

Problem with unicode verbose_names :(

I get an error when I try to do a syncdb when my models have unicode(greek) verbose_names .

I found out that this can be fixed in you change the like 168 of models.py from

meta_fields['verbose_name'] = ('historical ' + str(model._meta.verbose_name))

to

meta_fields['verbose_name'] = ('historical ' + unicode(model._meta.verbose_name))

Best regards!

"Changed by" displays None when change occurs outside of admin

When a model is changed within django's admin app, the "Change history" tab displays which user made the change (under Changed by).

However, when the same change occurs outside the admin app, "None" is shown.

Is this the expected behaviour? If so, how can I log the user that made the change?

Thanks!

add "add to installed apps"

remember to add to the installation guide the recomendation to add "simple_history" to the installed apps.

save_without_historical_record() Does not work

I am struggling to make this work for 2 days but i cant find a way to do it (i am not a real pro in django). I know this may be not for the issue section but i dont know where else to put it.
Here is the case i have a model :

class Artikel(models.Model):
    treaty = models.ForeignKey(Treaty)
    parent = models.ForeignKey(Heading, null=True, blank=True)
    artikel_type = models.CharField(max_length=255, null=False, blank=False, choices=ARTIKEL_TYPE_CHOICES)
    title = models.CharField(max_length=255, null=True, blank=True)
    history = HistoricalRecords()

and here is my save() method

def save(self):
    self.save_without_historical_record()

Am i missing something crucial, because i am getting this error :

AttributeError at /admin/treaties/artikel/329/
skip_history_when_saving

Give ability to compare two history versions

Similar to how a Wiki works, it would be very useful to be able to compare the differences between two historical versions or to compare the differences between the current version and a historical version. The comparison tool should look at all fields that are common to both versions and show a visual diff between each pair's values.

django-reversion has an add on to give this comparison ability. It would be great if django-simple-history had the functionality as well.

https://github.com/jedie/django-reversion-compare

HistoricalRecord on abstract parent model class doesn't work

class TestBase(models.Model):
  class Meta:
    abstract = True
  history = HistoricalRecords()

class Test(TestBase):
  name = models.CharField(max_length=128)

Using this pattern, History is not available for Test model. Works when you specify history with Test model explicitly.

Add comprehensive tests for historical model location/name

This should help clarify the regressions that may be present when upgrading to Django 1.7 (with the new app limitations).

Tests should verify that under various conditions that Django's get_model returns the expected historical model.

Related to #57.

templates missing from pypi packages

The templates directory is missing from the tarballs uploaded to pypi.

from simple_history.admin import SimpleHistoryAdmin
admin.site.register(MyModel, SimpleHistoryAdmin)

there is a history button in the admin page but it fails miserably to find the templates.

save on django admin tool is not saving the history

Taken from Bitbucket issue tracker:

tried the poll app on "manage.py shell". History got saved. After altering a key in django admin tool (via web ui), the history is not getting saved.

This bug hasn't been verified yet.

Tracking a Custom User

Perhaps just a limit of Django at the moment, but I can't seem to find any way to track a custom User object since HistoricalRecords() starts model validation before the custom user object is installed.

accounts.historicaluser: 'history_user' has a relation with model accounts.User, which has either not been installed or is abstract.

Problem with custom user and HistoricalRecords

Maybe it is a duplicate of #56

I tried that: https://gist.github.com/csarcom/9934966
and i got this error:

raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed

If I remove history = HistoricalRecords() from my model History and add register(CustomUser) from simple_history it works... but, is there a way to work with history = HistoricalRecords() instead register() ?

Getting error when trying to view a models history

I am using Django 1.5 and django-simple-history 1.3 and am running into the following error when accessing a models history:

Reverse for 'auth_user_change' with arguments '(1,)' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/contract/contract/1/history/
Django Version: 1.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'auth_user_change' with arguments '(1,)' and keyword arguments '{}' not found.
Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py in render, line 424
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.2

Error during template rendering

In template /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/simple_history/templates/simple_history/object_history.html, error at line 30
Reverse for 'auth_user_change' with arguments '(1,)' and keyword arguments '{}' not found.

a href="{% url admin_user_view action.history_user_id %}">{{ action.history_user }}</a

Fix broken tox tests with Python 2.6

Failure:
ERROR: InvocationError: '/home/trey/repos/django/django-simple-history/.tox/py26/bin/coverage run -a --branch setup.py test'

Summary output:

ERROR:   py26-1.3: commands failed
ERROR:   py26-1.4: commands failed
ERROR:   py26: commands failed
ERROR:   py26-trunk: commands failed
  py27: commands succeeded
ERROR:   py27-trunk: commands failed
  py27-1.5-nosouth: commands succeeded

Historical model doesn't include fields inherited from superclass

I ran into this issue trying to add simple_history to a model using django-mptt ( https://github.com/django-mptt/django-mptt/ )

The model in question extends MPTTModel, which adds the fields lft, rght, tree_id and level to the model. However, if I try and save the model, it fails, with the exception:

TypeError: 'rght' is an invalid keyword argument for this function

I did some digging, and when the create_history_model() executes, these fields did not exist. The contents of model._meta.fields at that time was:

[<django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: name>, <django.db.models.fields.SlugField: url>, <django.db.models.fields.CharField: code>, <mptt.fields.TreeForeignKey: parent>, <django.db.models.fields.TextField: hidden_js>, <django.db.models.fields.related.ForeignKey: faculty>]

However, if I opened up a django shell, and output the contents of the same variable, I got:

[<django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: name>, <django.db.models.fields.SlugField: url>, <django.db.models.fields.CharField: code>, <mptt.fields.TreeForeignKey: parent>, <django.db.models.fields.TextField: hidden_js>, <django.db.models.fields.related.ForeignKey: faculty>, <django.db.models.fields.PositiveIntegerField: lft>, <django.db.models.fields.PositiveIntegerField: rght>, <django.db.models.fields.PositiveIntegerField: tree_id>, <django.db.models.fields.PositiveIntegerField: level>]

Which does have the additional fields. My conclusion is that the class has not yet been properly initialized at the time class_prepared is fired.

history property not picked when model class is in a models directory

I have multiple model files under a models directory. Example:

    myapp/
            models/
                        __init__.py
                        model1.py
                        model2.py
                        model3.py

The model classes within model1.py, model2.py, etc are using an app_label and have a history property. Example:

    class Meta:
        app_label = 'myapp'

    history = HistoryRecords()

The history property is not getting picked up by south as a schema change (not sure about syncdb).

However, when I use a "traditional" app directory structure with a single models.py file, everything works. Example:

    myapp/
        models.py

Does this require an enhancement? Perhaps I am doing something wrong on my end. Thanks.

Foreign keys which aren't integers

If I have a model which defines a custom primary key like this:

iso_code = models.CharField(max_length=3, primary_key=True)

When the model is referred to as a foreign key saving fails as the history table automatically uses integer fields for ForeignKey fields. I attempted a fix but I am having some issues with it. What I tried was this

https://github.com/essencedigital/django-simple-history/commit/ccf363c4209e53d308ee408e0bdf98900b58bd77

But it doesn't work with what appears to be a foreign key that looks like this

last_issued_version = models.ForeignKey('io.InsertionOrderVersion', null=True, blank=True, related_name='insertionorder_last_issued_version')

Any ideas?

Thanks

The as_of method should also work without an instance

Hello,

first of all thank you for the nice project !

Also, I'd like to ask if you can make as_of work in the manager and not only on instances. What I mean is that if I have a Ship model having historical_records I'd like to do something like that:

old_ships = ships.models.Ship.history.as_of(past_date)

and easily see the status of my ships at the past_date!

I know that I could query my ships now and for each ship returned use the as_of but the recommendation would save a lot of SQL queries !

Thanks !

changed_by field with through model(that already has User ForeignKey)

This is what I have:
https://gist.github.com/csarcom/9938033

Problem:

Exception: <class 'apps.user.models.CustomUserAccount'> has more than 1 ForeignKey to <class 'apps.user.models.CustomUser'>

My model should be ok with two foreign key to the same model using related_name right? But, since it is a through model, i guess django does not support it[1].

Any idea how can I save history_user on that model?

[1] https://code.djangoproject.com/ticket/8618

more examples?

Apologies -- this is not really an issue, per se, but a request for some more examples, perhaps in the wiki section?

For example, what is the right way to search through an HistoricalRecord list? Can I get the last record before or after a certain date? Get the first or penultimate HistoricalRecord?

custom user model not working with SimpleHIstoryAdmin

If my user model is not auth.User then rendering object_history.html template fails with NoReverseMatch.

The problem is in line 28.

If I change auth_user_change to myapp_user_change everything works, but it's not a general fix =)

Proper app and model name can be found in AUTH_USER_MODEL but, as far as I understand, there is no template filter which can pull them out.

Possible fixes are

  • remove link from template =)
  • add user_app and user_model to context in SimpleHistoryManager. This may help.

Add documentation

Some things to note in documentation:

  • Explain how to use custom admin views (add simple_history to INSTALLED_APPS and inherit admin)
  • Recommendantions on version-controlling with South
  • Example of version-controlling Django auth's User model.
  • document simple_history.register usage
  • Example of using _history_user attribute (see gist:5439427 and django-cuser)
  • Add documentation for as_of method on historical record manager
  • Add documentation for most_recent method on historical record manager

tag 1.2.1 is missing

package available on Pypi is 1.2.1 however there is no tag 1.2.1 in the code repo.
thanks!

View deleted instances from admin page

The SimpleHistoryAdmin allows the history of a instance that still exists to bee seen. It would be great if there would be a way to view a list of deleted instances, and see their histories.

Django 1.7 & pytest-django break simplehistory models

Most of the discussion around this is in pytest-dev/pytest-django/issues/119
however it relates to Django 1.7c1 and AppLoading. The relevant portion of the logs looks like

simple_history/models.py:120: in create_history_model
    app = apps.app_configs[model._meta.app_label]
E   KeyError: ...

https://github.com/treyhunner/django-simple-history/blob/master/simple_history/models.py#L120

pytest-django is careful to avoid loading django & django settings during test discovery which is different from most of the django test runners. However, simple-history appears to be exploiting a loophole in AppConfig which makes it dependent on the order that things are loaded.

I'm still wrapping my head around the code involved from pytest-django, django 1.7 and simplehistory but a reading of https://docs.djangoproject.com/en/dev/ref/applications/#django.setup I think says simplehistory should be modified to defer creation of models until get_app_config() is usable?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.