In this article, I will display the detail page of "Todo List". I'm thinking of people who are just starting to learn Django. If you read the articles up to the last time, I think it will go smoothly.
Articles up to the last time ↓ ↓ ↓ Procedure to create application with Django with Pycharm ~ Preparation ~
Django ~ settings.py edition ~
Django ~ Let's display it in the browser ~
Django-TodoList ① ~ Let's display the list ~
First of all, we will connect the URL to'urls.py'. Open the application'urls.py'. (If you have not created it because it is not prepared by default, type the following in the terminal.)
#Move to application directory
$cd application name#This time "to do"
#urls.Create py
$ touch urls.py
When you open'urls.py'(if you can create it), add the following.
from django.urls import path
from .views import TodoList, TodoDetail
urlpatterns = [
path('list/', TodoList.as_view()),
path('detail/<int:pk>/', TodoDetail.as_view()), #Connecting detail screens
]
'int: pk' specifies which data to display. You will actually enter it later, but by adding'detail / 1 /'to the end of the URL, the first data will be displayed. By the way, if you look at the details of each data on the management screen, you can see that the number is displayed at the end of the URL part n.
You can think that'TodoDetail.as_view' brings the'TodoDetail class in'view.py'.
Next, edit'view.py'.
from django.shortcuts import render
from django.views.generic import ListView, DetailView #Import DetailView
from .models import TodoModel
class TodoList(ListView):
template_name = 'list.html'
model = TodoModel
class TodoDetail(DetailView): #Define TodoDetail class
template_name = 'detail.html' #'template'Is'detail.html'Specify
model = TodoModel #The model is'TodoModel'Specify
As I explained in the previous article,'views.py' works to collect materials, so I specify'tempalte'and the model.
We will make some changes from the previously created'models.py', so add the following.
from django.db import models
from django.utils import timezone
class TodoModel(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
deadline = models.DateTimeField(default=timezone.now)
Editing is now complete.
Let's check if it can be displayed immediately.
Type the following into the terminal:
$ python manage.py runserver
The URL will be displayed, so click it to jump to the browser. When you reach the browser, add'detal / 1 /'to the end of the URL.
Then you should be able to see that the contents of the first registered data are displayed.
This time, I decided to display the detailed screen of each data. We will continue to add articles in the future, so we would appreciate it if you could refer to it.
Recommended Posts