Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Loading another template on click of a button

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.

like image 547
star98 Avatar asked Jan 09 '15 16:01

star98


2 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>
like image 158
catavaran Avatar answered Oct 24 '22 13:10

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 :)

like image 22
Gayathri Avatar answered Oct 24 '22 12:10

Gayathri