Django: Loading another template on click of a button

Question:

I’ve been working on a django project for a few weeks now, just playing around so that I can get the hang of it. I am a little bit confused. I have a template now called “home.html”. I was wondering if there is anyway for me to have another template called “profile.html” to be set as a link on the home.html template? I have a button that when clicked, should take me directly to the profile.html page, but as I was doing research on this topic, I was getting mixed answers. Some people stated to create a view and have that load the html using javascript, while others stated that just writing the path to the 2nd page template in tags would be easier.

What is the most correct way of getting this done?

I looked at this link: Rendering another template from a button click in Django to try to get a better understanding, as it was the one other question that was closest to what I was asking, but it confused me even more as the django lingo is somewhat confusing for me to understand as a beginner.

Thank you in advance for any help you can provide.


EDIT: To sum it up: I am on the home page currently. There is a button that says “View your profile”. Once that button is clicked, I want to leave the home page and have the new page “profile.html” to be loaded on the screen.

Asked By: star98

||

Answers:

“Most correct way” is to create view which will load your “profile.html” template. I suggest to use generic TemplateView.

Add this line to your urls.py:

from django.views.generic import TemplateView

urlpatterns = patterns('',
    url(r'^profile/', TemplateView.as_view(template_name='profile.html'),
                      name='profile'),
)

And in home.html use this snippet:

<a href="{% url 'profile' %}">Profile</a>
Answered By: catavaran

Instead of using TemplateView, you can also just have

<a href="{% url 'profile' %}">View your profile</a>

in your home template. In your project’s main urls.py just add url of your profile template.

url_patterns = [
        url(r'profile/',profile_view,name="profile")
]

Have a function defined as profile_view in views.py.
The link will work then 🙂

Answered By: Gayathri

Use TemplateView, you can get load a template without doing much.

In your project’s main urls.py, add the following.

from django.urls import path
from django.views.generic import TemplateView


url_patterns = [
        path('index/', TemplateView.as_view(template_name='index.html'),
                        name='index'),
]

Then in your template direct the href like this:

<a href="{% url 'index' %}">Your homepage</a>

the url will work like a charm now.

hope this helps 🙂

Answered By: Rai Shahnawaz