Home > Software design >  Django view return data
Django view return data

Time:12-31

I have a view that returns an HTML response using render. The data returned is specific to a template.

If I want to consume that data on another page, should I write another view with the same logic, or is there a way to pass the data from view 1 to view 2

view return render(request, 'pages/project_details.html', {"project": project,

urls path('show_project_details/<project_id>', view=show_project_details, name="show_project_details"),

I know that a view is just a function, which takes a request and does something with it, but I don't get how I make a request to a view within a template and consume the response within an existing page.

Example here:

## filename: views.py

from django.shortcuts import render
from .models import Team

def index(request):
    list_teams = Team.objects.filter(team_level__exact="U09")
    context = {'youngest_teams': list_teams}
    return render(request, '/best/index.html', context)

I want to return the data within this context to home.html and index.html.

Hope this makes sense?

CodePudding user response:

You can use your urls.py to pass a variables through via the URL notation.

For example - Getting Team info:

template

{% for team in youngest_teams %}
    <a href="{% url 'get_team_info' team.id %}">Team</a>
{% endfor %}

url.py

path('team_info/<team_id>', view=team_info, name="get_team_info")

views.py

def team_info(request, team_id=None):
    team = Team.objects.get(id=team_id) #Information on team is passed.

CodePudding user response:

There are multiple cases in your case. Let me explain them one by one. Let's say you have two templates. One is template 1 and the other is template 2.

  1. If you want to use the same logic for template 1 and template 2. You can use a variable in the views.py & url.py and use a condition there on that variable which is team_id in your case. E.g.
def index(request, team_id):
    list_teams = Team.objects.filter(team_level__exact="U09")
    context = {'youngest_teams': list_teams}
    if team_id == 1:
         return render(request, '/best/index.html', context)
    elif: team_id == 2:
         return render(request, '/best/template2.html', context)

And in urls.py, you can write:

path('team_info/<int:team_id>', view=team_info, name="get_team_info")
  1. If you don't want the variable in the views and URLs. Then you can write different views with the same code in views.py. But in the case of multiple ids, it will cause code duplication.
  • Related