Reputation: 133
i have serial numbers in my database , each serial number have coded date in it, i want to get the date from the serial number and print in data table
my view.py
from .models import Module
month = {'1': 'Jan', '2': 'Feb', '3': 'Mar', '4': 'Apr', '5': 'May', '6': 'Jun', '7': 'Jul', '8': 'Aug', '9': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}
year = {'L': '2010', 'M': '2011', 'N': '2012', 'O': '2013', 'P': '2014', 'Q': '2015'}
@login_required()
def modules(request):
modules = Module.objects.all()
for module in modules:
day = module.serial_number[:2]
mon = module.serial_number[2:3]
mon = [val for key, val in month.items() if mon in key]
year1 = module.serial_number[3:4]
year1 = [val for key, val in year.items() if year1 in key]
print(module.serial_number, day, mon, year1)
total_modules = modules.count()
context = {'modules': modules, 'total_modules': total_modules,
}
return render(request, 'modules/modules.html', context)
when print(module.serial_number, day, mon, year1)
im getting what i want
044PGG01501S 04 ['Apr'] ['2014']
127QGG01501S 12 ['Jul'] ['2015']
but cant make this work in template
any ideas
Upvotes: 0
Views: 100
Reputation: 336
I would strongly advice not to use such loops in case of simple properties, using 'annotate' function of django or writing properties of a model such as: day, mon, year1 is both viable options - better than using forloop in view.
Annotation: https://docs.djangoproject.com/en/3.1/topics/db/aggregation/ Writing properies: https://docs.djangoproject.com/en/3.1/topics/db/models/#model-methods
Forloop in django template: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#for
So basicaly in template you should be able to use
{% for module in modules %}
{{module.serial_number}} {{module.day}} {{module.mon}} {{module.year1}}
The problem that you have is that you are not creating properties of an object in forloop (if you insist on using this approach) but you make general variables, you should use module.day instead of day, and so on.
Upvotes: 1