I'm currently working on an app for logging changes to model fields. The changes are logged as a JSON string
{"field": field.name, "old_value": old_value, "new_value": new_value}
in atextfield
.How can I get specific keys/values of the JSON string? Current code:
views.py
def userChangelog(request, pk): user = User.objects.get(pk = pk) changelogs = ChangeLog.objects.filter(user_id = pk) context = { 'user': user, 'changelogs': changelogs, } return render(request, 'users/backend/user/user_changelog.html', context)
template
{% for changelog in changelogs %} <p>1. {{ changelog.user }}</p> <p>2. {{ changelog.changes }}</p> <p>3. {{ changelog.date_of_change }}</p> {% endfor %}
Ideally, I would like to do
<p>2. {{ changelog.changes.field }} changed from {{ changelog.changes.old_value }} to {{ changelog.changes.new_value }}</p>
, but can't seem to figure out how to translate only part of the query tojson.loads
, and display it in the template.Edit - ChangeLog model
class ChangeLog(models.Model): user = models.ForeignKey(User, related_name = 'changed_by', on_delete = models.CASCADE) content_type = models.ForeignKey(ContentType, models.SET_NULL, verbose_name = _('content type'), blank = True, null = True,) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') changes = models.TextField(_('changes'), blank = True) date_of_change = models.DateTimeField(_('change time'), default = timezone.now, editable = False,) objects = ChangeLogManager() class Meta: verbose_name = _('Change log entry') verbose_name_plural = _('Change log entries') def change_message(request, obj, old_instance): new_instance = obj.objects.get(pk = old_instance.pk) ct = ContentType.objects.get_for_model(new_instance) for field in obj._meta.get_fields(): if isinstance(field, models.ManyToOneRel): continue old_value = getattr(old_instance, field.name) new_value = getattr(new_instance, field.name) if old_value != new_value: change_message = json.dumps({"field": field.name, "old_value": old_value, "new_value": new_value}) ChangeLog.objects.log_update( user = request, content_type = ct, content_object = new_instance, object_id = new_instance.pk, changes = change_message, date_of_change = timezone.now() )
score:2
If you do not wish to use a third party package. You could add a property to your ChangeLog
model that parses and returns the changes JSON. cached_property is useful as it stops you parsing the changes on every access
@cached_property
def changes_dict(self):
return json.loads(self.changes)
Than you can use it in your template
{% for changelog in changelogs %}
<p>1. {{ changelog.user }}</p>
<p>2. {{ changelog.changes_dict.field }}</p>
<p>2. {{ changelog.changes_dict.old_value }}</p>
<p>2. {{ changelog.changes_dict.new_value }}</p>
<p>3. {{ changelog.date_of_change }}</p>
{% endfor %}
Credit To: stackoverflow.com
Related Query
- Django retrieving JSON key/value from JSON string in textfield
- Django REST framework: create JSON fragments from string
- How do I retrieve key from value in django choices field?
- Get key value from display value from choices in Django
- Django get value from JSON data
- Retrieving JSON from HttpResponse from Django view
- Can't get the value by key from request.session; I use django
- Retrieving a foreign key value in Django Rest Framework
- JsonResponse from Django not sending the mentioned key value pair to Reactjs
- Django template cannot access JSON Key in duplicate quotations: {" 'Key' ": " Value "}
- How to escape quotes when setting a javascript string to the value propagated from a Django variable?
- Creating a nested JSON from a value in Django Rest Framework
- How to extract JSON value from a list and render it in a django model form?
- Django foreign key value from template
- Django Rest Framework: Default foreign key to value from request
- Can't index parsed JSON string from backend, it returns an undefined value
- Loading data from Json file into PostgresSql causes: ERROR "duplicate key value violates unique constraint - already exists."
- How to get value from form field in django framework?
- Retrieving a Foreign Key value with django-rest-framework serializers
- django template display item value or empty string
- Foreign key from one app into another in Django
- how to get field type string from db model in django
- How to get key value in django template?
- Preventing django from appending "_id" to a foreign key field
- Returning JSON array from a Django view to a template
- Accessing Primary Key from URL in Django View Class
- how to write a query to get find value in a json field in django
- django bytesIO to base64 String & return as JSON
- django update_or_create gets "duplicate key value violates unique constraint "
- Sending post data from angularjs to django as JSON and not as raw content
More Query from same tag
- django-reversion how to get user-id
- AppConfig.ready() is Running Twice on Django Setup (Using Heroku)
- Can't install discount with pip: error: command 'cc' failed with exit status 1
- add +1 hour to datetime.time() django on forloop
- Using variables with a django template
- handlers for specific Exception
- Create Django Table displaying information about users
- Post method in angular giving error 406 (Not Acceptable)
- Django/ python validate JSON
- Django delete cache with specific key_prefix
- Very simple web service: take inputs, email results
- How to use annotate in query set to extract a count of type in a location?
- Custom social sing up form
- Securely storing account balances in a database?
- Unusual setdefault's in Django