Home > other >  How to use some variable that call a function to put inside of HTML template in DJANGO
How to use some variable that call a function to put inside of HTML template in DJANGO

Time:09-28

  • I need to use that function below, here is in util.py

    def get_entry(title):
        try:
            f = default_storage.open(f"entries/{title}.md")
            return f.read().decode("utf-8")
        except FileNotFoundError:
            return None
    
  • Then I put that in my views.py with the var "get"

    def getFunction(request):
        return render(request, "encyclopedia/index.html", {
            "get": util.get_entry()  
        })   
    
  • So I want to use that function in my index.html

    {% block body %}
        <h1>All Pages</h1>
    
        <ul>
            {% for entry in entries %}
                <a href="{% get %}"><li>{{ entry }}</li></a> //{% get %} doesn't work
            {% endfor %}
        </ul>
    {% endblock %}
    
  • The only for is to show up a list with 5 items and inside of li, using entry I can display all five items (e.g: apple, banana, tomato, pear, grape)

  • I need to use href because When I click it will to another folder/file .md that will be writed about apple for example

  • I wanna use that function to take in my file .md

  • If you need more informations just ask me. thank u. :)

CodePudding user response:

You can add an @property on models.py for the app the call entries.your_function

CodePudding user response:

You can try this

class YourModel(models.Model):

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

    # Add a property to your model
    @property
    def yourFunction(self):
        # steps
        return 'Hello from your template!'

Next just call it like this in your template

{{ your_model_instance.yourFunction }}

You will see

Hello from your template!
  • Related