How to call a view method in html?

Asked

Viewed 1,736 times

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 now want to call this function which 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 {%home %} and tried to use the specific path of the file as well, but it gives me a rendering error as I am using {% extend base.html %} and the navbar is affected so I can modify it.

2 answers

2

It would be better to 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 html:

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

The name 'home' in the link is the name q vc defined in the url.

1


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

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

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

py views. - 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.py urls that way:

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

Urls with Namespaces

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

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

And within your project’s.py urls, you group your app’s set of urls that way:

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 in 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>
  • 1

    One more for the namespace, did not know. ++

Browser other questions tagged

You are not signed in. Login or sign up in order to post.