[Fixed]-How to configure Django views and urls to render specific templates

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.home
127.0.0.1:8000/something will executed code of views.something
127.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

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

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

def post_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

0πŸ‘

  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:

def home(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.

πŸ‘€pythad

Leave a comment