creating a custom template tags in django


creating a custom template tags in django



I am new to Django and I am trying to create custom tags in django



my custom tag file templatetag/custom_tag.py


templatetag/custom_tag.py


from django import template
from model_file.models import my_Model

register = template.Library()

@register.simple_tag
def get_custom_tag_fn():

return my_Model.objects.all()



my html file


{% load custom_tag %}
{% get_custom_tag_fn as queries %}
{% for query in queries %}
{{query.json_my_model_data}}
{% endfor %}



I am not getting any output or error from this code. Can anyone point where I went wrong.



for extra information my model.py looks like


model.py


from django.db import models
from jsonfield import JSONField

class my_Model(models.Model):
json_my_model_data = JSONField()





Are there any instances in my_Model?
– Willem Van Onsem
Jul 1 at 9:43


my_Model





my_Model doesn't seem to have a val1 field.
– Daniel Roseman
Jul 1 at 9:44


my_Model


val1





sorry, I had made a mistake there it's not val1 its json_my_model_data
– BczImHappy
Jul 1 at 10:04





And to answer to @WillemVanOnsem is, yes I have 2 objects.
– BczImHappy
Jul 1 at 10:10






Instead of iterating and run {{queries}}, I get <QuerySet [<my_Model: my_Model object (1)>, <my_Model: my_Model object (2)>]>
– BczImHappy
Jul 1 at 10:14



{{queries}}


<QuerySet [<my_Model: my_Model object (1)>, <my_Model: my_Model object (2)>]>




1 Answer
1



It looks like my_Model doesn't have a val1 field, you may need to change your template to the following if you want to show json_my_model_data field in your data model my_Model:


my_Model


val1


json_my_model_data


my_Model


{% load custom_tag %}
{% get_custom_tag_fn as queries %}
{% for query in queries %}
{{query.json_my_model_data}} # to get model's `json_my_model_data` content.
{% endfor %}



On the top of that {{query.json_my_model_data}} will only be executed and show the contents of json_my_model_data if queries queryset has at-least one my_Model object from the database.


{{query.json_my_model_data}}


json_my_model_data


queries


my_Model



More on custom template tags.



Hope it helps.





sorry. I make a mistake while typing here, actually, the value is json_my_model_data in my program.
– BczImHappy
Jul 1 at 10:07





no worries, happens.
– mrehan
Jul 1 at 10:08






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API