jundymek
jundymek

Reputation: 1043

Getting values from django model for further use in view

I have a model with 3 fields (name, url, date). How can I get url in my view and put it inside method?

sites = Site.objects.all().order_by('date')[:3]

I need to get host from url (http://www.example.com to example.com). I have a class for this task:

class SiteThumb():

    def get_site_thumb(self, url):
        host = urlparse(url).hostname
        if host.startswith('www.'):
            host = host[4:]
        return(host)

I would like to use it later in my template (something similar to {{ site.url }} but with use of variable 'host' related to particular 'site' object).I can not deal with it. I can with another view where is only one site:

def site(request, category_slug, subcategory_slug, id):

There is id which I can simply assign to particular object. In my base view

def index(request):

I have to load a couple of objects. Thanks for any clues.

Upvotes: 2

Views: 64

Answers (1)

Rajesh Yogeshwar
Rajesh Yogeshwar

Reputation: 2179

One approach is model methods.

For eg. Site is a model in which you have the said three fields url, name and date. Now you can define a model method for Site model which you can access in template. It can be done in this way.

class Site(models.Model):

    url  = field
    name = field
    date = field


    def hostname(self):
        #It is copy paste of your implementation
        host = urlparse(url).hostname
        if host.startswith('www.'):
            host = host[4:]
        return host

In your template on every Site instance this method can be accessed as {{ site.hostname }}.

Upvotes: 3

Related Questions