[Django]-How to call model methods in template

6👍

Pass the model instance to template via context

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['instance'] = Department.objects.get(id=1)
    return context

<a href="{{ instance.get_url }}"></a>

0👍

I think you can do it like this:

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

Then you can use it in template like this:

 <a href="{{ object.get_url }}"></a>

Update

For accessing the instance of model in template, you need to send it to Template through context. In a function based view, you can try like this:

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)
👤ruddra

Leave a comment