How to call a method of views in html?

0

I created the following method in the views.py file:

def home(request):
   name = 'Jacinto'
   args = {'myName' : name}
   return render(request, 'accounts/home.html', args)

I want to now call this function that redirects me to the home.html file in the following html code:

<ul class="nav navbar-nav">
   <li><a href="{% home %}">Home</a></li>
</ul>

I tried to use {% home%} and already tried to use the specific path of the file, but it gives me a render error, since I am using a {% extend base.html%} and navbar is affected to I can modify it.

    
asked by anonymous 11.01.2018 / 16:29

2 answers

1

You can create a view that renders a template as follows:

urls.py - In your urls, create the route that calls the view and a name (this name you will call the template:

url(r'^accounts/home', views.home, name='home'),

views.py - Then create the view and context attributes:

def home(request):
   context = {'name' : "Fabimetabi"}
   return render(request, 'accounts/home.html', context)

accounts / home.html - Now in the template, you call the name of your view created in urls.py like this:

<ul class="nav navbar-nav">
   <li><a href="{% url 'home' %}">Home</a></li>
</ul>

Urls with Namespaces

You can also use the Namespaces to organize better their routes. Within your app, you create a file called urls.py as well.

url(r'^home', views.home, name='home'),

And within the urls.py of your project, you group the urls set of your app like this:

url(r'^accounts/', include('accounts.urls', namespace='accounts')),

Finally, in your template you call the url by passing the namespace.

<ul class="nav navbar-nav">
    <li><a href="{% url 'accounts:home' %}">Home</a></li>
</ul>

This leaves the code and url calls in the template more organized. If you have other apps on the menu it would look like this, for example:

<ul class="nav navbar-nav">
    <li><a href="{% url 'accounts:home' %}">Home</a></li>
    <li><a href="{% url 'videos:home' %}">Videos</a></li>
    <li><a href="{% url 'accounts:register' %}">Cadastrar</a></li>
</ul>
    
11.01.2018 / 18:28
2

You'd better create the link in the url file:

url(r'^accounts/home', views.home, name='home'),

In the home view you render the template. And call the link in the html:

<li><a href="{% url 'home' %}">Home</a></li>

The name 'home' in the link is the name you defined in the url.

    
11.01.2018 / 17:59