beginners
beginners

Reputation: 325

How to call model methods in template

I want to call the model method get_url() in the tag in the template

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>

Upvotes: 3

Views: 7905

Answers (2)

Atley Varghese
Atley Varghese

Reputation: 576

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>

Upvotes: 6

ruddra
ruddra

Reputation: 51948

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)

Upvotes: 0

Related Questions