Skip to content

Instantly share code, notes, and snippets.

@julzhk
Created August 14, 2019 15:43
Show Gist options
  • Save julzhk/79d92edc7dcdd69ee23f78ab9b359c88 to your computer and use it in GitHub Desktop.
Save julzhk/79d92edc7dcdd69ee23f78ab9b359c88 to your computer and use it in GitHub Desktop.
Are Django fields being used in my templates?
import os
from subprocess import check_output
from django.apps import apps
# Are my django model fields actually being used in my templates? This function lists the unused ones.
# Note - scans for *html and api.py (Django Rest Framework) files
def find_str(needle, full_path='/home/myacct/Projects/my_project/'):
try:
f = check_output(f'/bin/grep -nr --include="*.html" "{needle}" ' +
' --include="api.py" '+
'{full_path}',
shell=True
)
except Exception as err:
return False
return True
def show_usages(app_to_scan):
app_models = apps.get_app_config(app_to_scan).get_models()
for model in app_models:
print(model.__name__)
print('-'* len(model.__name__))
fields = model._meta.get_fields()
for f in fields:
fld = str(f).split('.')[-1:][0]
if not find_str(fld):
print(fld)
show_usages('product')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment