[Answer]-Django model inheritance and subclass access in templates

1๐Ÿ‘

โœ…

Well my preference would be to do error handling in the views and not in the templates. There are a lot of ways you can go about doing this, following is a simple example.

###helpers.py
import models

def get_profile1_or_profile2(user):
    profile = get_instance_or_none(models.ProfileTypeOne, user=user)
    if profile is None:
        profile = get_instance_or_none(models.ProfileTypeTwo, user=user)
    return profile

def get_instance_or_none(model, **kwargs):
    try:
        result = model.objects.get(**kwargs)
    except:
        result = None
    return result


###views.py
import helpers

def some_view(request):
    """
    This view renders some template.
    """

    profile = helpers.get_profile1_or_profile2(request.user)
    if profile:
        # Render the template and pass in the profile object
    else:
        # Redirect to 404 or whatever kind of error handling.

Then in your templates you can simply do {{ profile.get_status }}

Also as you said:

the reason I want to put this logic into template, is because that template will be extended multiple time, and this basic logic should be in all templates, therefor forcing me, in case of transferring logic into view part, invoking some code multiple times, instead of one.

how would transferring the logic to views, invoke code multiple times. I mean it depends on the requests you make, No matter where your code lies either in templates or in views. This is how a request would work in both the cases.

In case of views:

Request Made โ€“> Url sends request to views โ€“> CODE RUNS HERE โ€“> renders the template

In case of templates:

Request Made โ€“> Url sends request to views โ€“> view renders the template โ€“> CODE RUNS HERE

๐Ÿ‘คAmyth

Leave a comment