How To Configure Django Views And Urls To Render Specific Templates
Solution 1:
- Include urls of your
myapp
app inmysite/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
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
- Add your templates in
myapp/templates/myapp/
. Addhome.html
andsomething.html
.
Now forget, the `.html
Solution 2:
- You create a
url
(with attachedview
to it). - 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"