Django provides a generic view. There are CreateView, UpdateView, DeleteView, ListView, DetailView, etc.
This time, we will use ListView to create a list page.
/crud/blog/view.py
from django.views.generic import ListView
from .models import Post
class PostListView(ListView):
#Model specification
model = Post
#Describe the path under html specified templates
template_name = 'blog/home.html'
#The name of the record group in the Post class
context_object_name = 'posts'
#Order: Descending date (latest is up)
ordering = ['-date_posted']
Creates the html file specified in view.py. Extract one record of posts (record group in Post class) with for and display the title, content, author, and posting date.
/crud/blog/templates/bolg/home.html
{% for post in posts %}
{{ post.title }}<br>
{{ post.content }}<br>
{{ post.author }}<br>
{{ post.date_posted }}<br>
{% endfor %}
URLConf is responsible for mapping URL patterns to views in Django. Write "Return this view if this URL is specified".
Please note that there are two files in urls.py. The first is /crud/config/urls.py. The entire project is set as the setting range. Load urls.py of each app by using include. The second is /crud/blog/urls.py. The setting range is the blog application.
Describe the setting to read urls.py of the blog application.
/crud/config/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('blog.urls')),
path('admin/', admin.site.urls),
]
"Http://127.0.0.1:8000/ returns a PostListView".
/crud/blog/urls.py
from django.urls import path
from .views import PostListView
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
]
Now that you're ready, let's view the view.
python manage.py runserver
Go to "http://127.0.0.1:8000/".
Did it look like the one above?
That's all for today.