Hi everyone i have a question about django template and models method include function parameter.
example code in models.py
class Item(models.Model):
name = models.CharField(max_length=30)
price = models.IntegerField()
owner = models.ForeignKey('User',on_delete=models.CASCADE)
def get_something(self,requestuser): # <-- pass request.user here
// calculate something here
return "output"
in views.py
def assets(request):
return render(request, 'index.html', {'items':Item.objects.filter(owner=request.user)})
in template
{% for item in items %}
<h1>{{item.name}}</h1>
<h2>{{item.price}}</h2>
<h2>{{item.get_something(request.user) }}</h2> <!-- How to inject request.user to get_something Here -->
{% endfor %}
You can use a custom tag for that case. Check this . I also had to build it for my project as I had to send arguments from template to my model's method. I created a folder in my app called templatetags and inside that folder was my __init__.py
and myTags.py
:
from django import template
register = template.Library()
@register.simple_tag
def call_method(obj, method_name, *args):
method = getattr(obj, method_name)
return method(*args)
then in template first I import my tags then I use my custom tag:
{% load myTags %}
{% call_method model 'method' argument1 argument2 argument3... %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.