Home > OS >  Calling a function from a function
Calling a function from a function

Time:01-02

I have some logic within a view that I want to have rendered on multiple templates.

How do I call the logic view from within another view and pass the data back to the view to be rendered?

This is a simple test I was doing.

def table_view(request):
    today = now().date()
    project_data = get_data_view
    context = {'projects_data':project_data}
    
    return render(request, "pages/project_table.html", context=context)

def get_data_view(request):
    project_list = Project.objects.all()
    context = {"project_list":project_list}
    return {'context':context}

The table view just renders a table, but the data within the table I want from the get_data_view

I know I can write the logic within the same view, but some of my views contain a lot of code and don't want to be repeating the same code to retrieve the same data.

CodePudding user response:

There's no special magic about the view functions - they're are quite a liberty to call other functions that do the rendering. So rather than think of table_view being a 'view' function, treat it just as a helper to the get_data_view function:

def table_view(request, context=None):
    if context is None: context=dict()
    today = now().date()
    context.update({'some_other_data':'some value'})
    
    return render(request, "pages/project_table.html", context=context)

def get_data_view(request):
    project_list = Project.objects.all()
    context = {"project_list":project_list}
    return table_view(request, 'context':context)

Or am I missing something about what you are trying to do?

As an aside, this is why I like class based views - you could define a 'TableView' class and then sub-class it for all the instances you need to a table with different data sources (or indeed use one of the addon django packages that already does this :-) ).

CodePudding user response:

You can just simply call the get_data_view function from your logic view function. The get_data_view will return your desired data and you can render it as you are already doing in the table_view function.

You are already doing most of the part. You should just modify the code as follows


    def table_view(request):
        today = now().date()
        project_data = get_data_view()
        context = {'projects_data':project_data}
        
        return render(request, "pages/project_table.html", context=context)
    
    def get_data_view():
        project_list = Project.objects.all()
        return project_list

According to your approach, your get_data_view returns a dictionary in which values are the Project objects. From my understanding of your problem, you just want the function get_data_view to return the data project_list so that you can render it on multiple templates. This should do the trick.

  • Related