Skip to content Skip to sidebar Skip to footer

How To Configure Django Views And Urls To Render Specific Templates

When I bring up 127.0.0.1:8000, the current page that show up is something.html template. I would need to make it appear index.html at first launch, then when I click on other part

Solution 1:

  1. Include urls of your myapp app in mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings

urlpatterns = [
    url(r'^', include('myapp.urls')),
    url(r'^admin/', include(admin.site.urls)),

]

Now, all urls, starting by 127.0.0.1:8000, will check if there is a view that can handle the request. I recommend you to read this to understand how Django URL dispatcher works : [Django documentation - URL Dispatcher] (https://docs.djangoproject.com/en/1.8/topics/http/urls/). 2. Add new route in your myapp.urls:

from django.conf.urls import url, patterns
from . import views

urlpatterns = patterns('',
    url(r'^$', views.home, name='home'),
    url(r'^something$', views.something, name='something'),
    url(r'^posts$', views.post_list, name='post_list'),
)

Now : 127.0.0.1:8000/ will executed code of views.home127.0.0.1:8000/something will executed code of views.something127.0.0.1:8000/posts will executed code of views.post_list Let's define these view now

3: Define the views in myapp.views :

from django.shortcuts import render

defhome(request):
    """
    Return home page
    """return render(request, 'myapp/home.html')

defsomething(request):
    """
    Return something page
    """return render(request, 'myapp/something.html')

defpost_list(request):
    """
    Return something page
    """# do what you want
  1. Add your templates in myapp/templates/myapp/. Add home.html and something.html.

Now forget, the `.html

Solution 2:

  1. You create a url (with attached view to it).
  2. In the view you render any html page you want.

If you use function based views your 'mysite.views.home' may look like:

defhome(request):
    ...
    return render(request, 'path/to/index.html')

and so on.

It's the basics so I won't talk about this much. You can find a good tutorial about mapping urls to views there.

Post a Comment for "How To Configure Django Views And Urls To Render Specific Templates"