- Contents show in the web pages are defined in
views.py
- if we want to use the variable in the models we predefined, we should import the models first
from .models import Blog, BlogType
- Generally, each function represents a page
# the page for the list of all blog
def blog_list(request):
context = {'blogs': Blog.objects.all()}
return render_to_response('blog/blog_list.html', context)
# the page for showing a exactly blog
def blog_detail(request, blog_pk):
context = {'blog': get_object_or_404(Blog, pk=blog_pk)}
return render_to_response('blog/blog_detail.html', context)
- using
render_to_response
to:
from django.shortcuts import render_to_response
- return the template
- sending the parameters to the template
- using
get_object_or_404
to get the values from the models
from django.shortcuts import get_object_or_404
def blog_detail(request, blog_pk):
context = {'blog': get_object_or_404(Blog, pk=blog_pk)}
return render_to_response('blog/blog_detail.html', context)
- filter the contents in the models
def blog_category(request, blog_type_pk):
blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
context = {'blogs': Blog.objects.filter(blog_type=blog_type),
'blog_type': blog_type,
}
return render_to_response('blog/blog_category.html', context)
Config urls
- we offen config urls in 2 parts:
1.
urls.py
in project folder
2.urls.py
in app folder
in app folder:
- import the
views
module
from . import views
- define your url for each view in
urlpatterns
usingpath()
function
urlpatterns = [
# http://localhost:8000/blog
path('', views.blog_detail, name='blog_detail'),
path('type/', views.blog_category, name='blog_category'),
path('', views.blog_list, name='blog_list'),
]
- the second parameter in
path()
is the parameter you define in the corresponding function inviews.py
- in this module each url will start with '/
/'
In project folder:
- import
views.py
(in general, we put the view for home page into the project folder) - import the
include
function
from django.urls import path, include
- use
include
function to include in urls in app folder,.urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('blog/', include('blog.urls')),
]