如何在模板中调用模型方法get_url() 我想在模板的标签中调用模型方法get_url()
models.py
class Department(Base):
department_name = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
def get_url(self):
ct = ContentType.objects.get(model='department')
url_name = ' %s:%s ' % (ct.app_label, ct.model)
return reverse(url_name, args=(self.object_id))
template.html
<a href="{% ? ... how to call the model method here.... ? %}"></a>
答案 0 :(得分:2)
通过上下文将模型实例传递给tempalte
41943040
答案 1 :(得分:0)
我认为您可以这样做:
class Department(Base):
department_name = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
def get_url(self):
ct = ContentType.objects.get(model='department')
url_name = ' %s:%s ' % (ct.app_label, ct.model)
return reverse(url_name, args=(self.pk)) # <-- Changed to self.pk to access primary key of the object
然后您可以在模板中使用它,如下所示:
<a href="{{ object.get_url }}"></a>
要访问模板中的模型实例,您需要通过上下文将其发送到模板。在基于函数的视图中,您可以尝试如下操作:
from django.shortcuts import render
def some_view(request):
department = Department.objects.first()
context = { 'object': department } # Here you can use any key in dictionary, I am using object. This key is accessible in template
return render(request, 'your_template.html', context)